TweetFollow Us on Twitter

Building Beans

Volume Number: 13 (1997)
Issue Number: 6
Column Tag: Javatech

Volume Number: 13 (1997)
Issue Number: 6
Column Tag: Javatech

Building Beans

by Will Iverson, Apple Computer, Inc.

Building a better application quicker with JavaBeans

Understanding JavaBeans

Over the last few years, we've heard a lot about component technologies, or software broken up into discrete, mixable sections. From a certain perspective, this includes such a broad umbrella of component technologies as OpenDoc, OLE, ActiveX, VBXs, OCXs, MacOS Extensions (INITs), Photoshop Plug-ins, Netscape Navigator Plug-ins, Control Strip Modules, DCMDs, and even BBEdit Extensions. This is a remarkable list, and includes some of the most interesting and powerful technologies available.

The latest entry to the field is one of particular interest to developers. JavaBeans, in the current incarnation, is a component architecture for development tool plug-ins. JavaSoft has hinted at plans to make JavaBeans spread further than tools -- how this will pan out remains to be seen. Given the recent introduction of JavaBeans, this article will cover what a JavaBean is and provide a brief introduction of how to build a JavaBean.

Most of the information provided in this article is based on the JavaBeans 1.0 specification available from JavaSoft. The reader is advised to frequently check the JavaSoft site at http://www.javasoft.com/ to stay abreast of the latest revisions to the specification.

To take full advantage of JavaBeans requires the use of the JDK 1.1, which on the MacOS means you will need to use MRJ 2.0. By the time this article is printed, a developer release of MRJ 2.0 should be available from http://applejava.apple.com/.

What is a JavaBean?

Taken directly from the specification: "a JavaBean is a reusable software component that can be manipulated visually in a builder tool." As of this writing, the only tool available for the Mac which comes close to implementing the spirit of JavaBeans is Symantec Visual Cafe, and this is the program from which screenshots below are taken.

The high level concept is simple -- there is a modular component architecture for the creation of developer components. Although some mention is made of JavaBeans as a compound document architecture, there is virtually no support for end user manipulation.

Figure 1.

In the builder tools above, you will see three windows. The toolbar is a clumping of the available components, the visual designer is the current visual interface being worked on, and the property list shows the editable values of the selected component.

Figure 2.

Figure 3.

Another critical element of JavaBeans is the capacity to link them together, to support passing events from one JavaBean to another as a way of triggering complex, possibly even cascading interactions. It's worth pointing out here that JavaBeans can be (and often are) not visually presented when the programming is running. A case in point is the example above -- a "timer" JavaBeans is a "visual" representation of a thread which fires at an given interval. The "timer event" is triggered when that interval is hit. When the "timer event" goes off, it tells the progress bar to update itself to the value specified, in this case a hypothetical connection progress status from a connect object's method. The timer isn't visual to the end user, but it can be manipulated through the property sheet by the developer.

You've probably already worked with some sort of visual builder tool -- ResEdit and the Metrowerks PowerPlant Constructor are examples. There are two fundamental problems with most of the mainstream tools that make them less than ideal.

  1. You can't add anything to the tool palettes.
  2. You have to switch between an environment for doing your visual design and writing your code (often having to close the visual design document before being able to run from your coding environment.
  3. The visual form builder typically has no good way to associate code with the visual elements -- typically strings or ID numbers are used, which can be a headache to track, especially for larger projects.
  4. Visual elements are limited to human interface, such as buttons, dialogs and menubars.

JavaBeans is designed to solve these problems.

Why is Visual Café Not JavaBeans?

When the Visual Cafe project was begun, JavaBeans didn't exist. Symantec worked with JavaSoft in designing the specification, but the bulk of the JavaBeans functionality, such as support for the new event model and introspection, (described later in this article) weren't available until the release of JDK 1.1. In order to "hack" around this limitation, Symantec developed a series of "descriptor" files. These '.desc' files are simple text files and can be found in the "Components" folder next to Visual Cafe. If you're interested, you can open these files up and take a look at how they were built. Symantec Visual Cafe 1.0.1 includes a pdf file describing the format of these desc files.

For a JavaBean developer, as long as you stick to the JavaBean "design patterns," also described below, you should be fine in the long term. If you'd like to make your JavaBean accessible to Visual Cafe 1.0, you can take a stab at trying to figure out the format to the desc files, but understand that these files are specific to Visual Cafe. The good news is that if you've done your job with the design patterns properly, you won't care - it'll just make your life easier.

How do JavaBeans Work?

Now that you've been given a taste of how a JavaBean is used, let's take a look at how a JavaBean is designed.

A JavaBean typically encounters three "classes" of people, the developer of the JavaBean (the "programmer"), the user of the JavaBean (the visual builder user), and the end user (or "client"). Note that the programmer and the visual builder may be the same person, but the assumption is that they are not.

  1. A programmer decides to create a JavaBean, either to share with others, to sell, or simply to make her code easier to reuse.
  2. The JavaBean is created using the JavaBeans design patterns.
  3. The JavaBean is packaged as a JAR file.
  4. The visual builder user adds the JavaBean to the her development environment's library with the "Add Component" command or similar action.
  5. The visual builder user drags the JavaBean from the component library to the project.
  6. The visual builder user sets the JavaBean properties and events with the visual builder or makes use of the JavaBean directly from traditional code.
  7. The visual builder user builds the application or applet and gives it to the client.
  8. The client uses the application, either as an applet, an application, or even as a Marimba channel.

Note that the "hard" work of developing the JavaBean by the programmer can be leveraged by dozens or thousands of visual builder users.

What Versions Of the MRJ Support Beans?

The initial release of the JDK 1.0 last year was less than ideal, and plagued by more than a few bugs. JavaSoft quickly realized that Java needed some quick patchup work, and came out with the JDK 1.02, essentially a bugfix version of the initial JDK specification. This is the version of the JDK which is incorporated into Netscape Navigator and is the foundation for the MacOS Runtime For Java (MRJ) 1.0. As anyone who has played with Java extensively realizes, JavaSoft didn't fix all of the bugs, and that's what takes so long for an implementation of the JDK to go final.

The MRJ 1.5, which may be available as a final release by the time this article is printed, is an implementation of the JDK 1.02 specification with the additional of the performance technology known as a JITc. Simply put, a JITc remembers that it has converted a section of bytecode to native code, and then caches that code. Typically, this results in an across the board CaffeineMark improvement of x10, with specific benchmarks ranging from no effect to over x20.

The MRJ 2.0, which will be available as a developer release this summer, is an implementation of the JDK 1.1, the new release from JavaSoft featuring a host of new features, many of which are required for Beans support, including Introspection, Reflection, RMI, Serialization, Internationalization, and other technologies.

The nice thing about the MRJ is that it isolates the Java VM from a specific application. You might want to install one version for customers, and use a different version for development purposes. That way, you can make your own decisions about your mix of bleeding edge and final release software, important when trying to stay on top of the latest technologies.

What are Design Patterns?

Design patterns are standardized ways of writing methods and interfaces. The simple example is of the property "Foo" which is set and retrieved with the functions "getFoo" and "setFoo." Design patterns may be used to specify events, public methods, and properties.

This is useful both for self-documentation as well as automatic code generation. When a property is set in a builder tool, it generates the code based on these patterns. For example, if the user sets the value of "Foo" to "Bar" then the builder would generate the code setFoo("Bar"); automatically (or use Serialization, but that's another topic).

Alternatively, a developer may provide all of this information through a "BeanInfo" function. Certain builder tools may be able to extract additional information through this mechanism, such as the icon to be drawn to represent a JavaBean or localized versions of the properties and events. Developers interested in the development of serious JavaBeans should review the documentation available from JavaSoft.

Note that successful design patterns require a few basic rules of thumb. First, different tools may wish to use the set and get methods in any order. Typically, this is not a problem -- you can call something a "blue, translucent rectangle" or a "translucent, blue rectangle" without changing the results, but certain designs will imply changes.

Design patterns exist for several standard concepts, including those listed below:

Simple properties are the basic "get" and "set" methods. To define a simple property, include methods of the form

public <PropertyType> get<PropertyName>()
public void set<PropertyName>(<PropertyType> x)

For example, you could define your own Rectangle class, and include the following methods:

public Color getColor()
public void setColor(Color x)

Note that the builder tool may recognize certain standard PropertyNames and provide certain standard pickers. For example, Visual Cafe brings up the Apple Color Picker when a property has the PropertyType Color.

A property may be formatted as public boolean is <PropertyName>(); format instead of a public <PropertyType> get <PropertyName>(); for better readability for English readers.

Indexed properties are also supported with the standard format of

public <PropertyType> get<PropertyName>(int i)
public void set<PropertyName>(int i, <PropertyType> x)

The New Event Model

Events are also defined by Design Patterns. The model for handling events has changed significantly in the JDK 1.1 from the 1.02 implementation. This is probably the area of your code which will require the most tweaking for general ports to JDK 1.1, regardless of whether or not you pay any attention to JavaBeans. While the JDK 1.1 supports the 1.02 event model, it does not support intermixing the 1.1 and the 1.02 models. Before we can talk about events and JavaBeans, we have to briefly dive into the new JDK 1.1 events.

JDK 1.1 introduces a new event model based on the concept of listeners. The idea is simple -- rather than poll for events repeatedly, your code registers itself as being interested in specific types of events. In other words, instead of asking every few seconds "what happened," your code simply says "tell me when this happens." This dramatically cuts down on the overhead for your code, especially in complex situations. For example, consider the mouse moved event -- with a polling model (or any event model without a registration mechanism, such as the JDK 1.02 AWT), this results in a fantastic number of events being generated (and much wasted processor time) -- even if no one is listening!

First, write the code which will handle the events. This class may implement one of the following:

ActionListener
AdjustmentListener
ComponentListener
ContainerListener
FocusListener
ItemListener
KeyListener
MouseListener
MouseMotionListener
TextListener
WindowListener

These are interfaces and therefore you will have to actually implement all of the methods for the class. This can be tedious, but you can optionally use one of the "adaptor" classes which provide empty methods for all of the corresponding Listener's methods. This allows you to use extends instead of implements, which may save you some code. You may have noticed that there are fewer adaptors than listeners -- some listeners, such as ActionListener, have a single method and an adaptor would serve no purpose:

ComponentAdapter
ContainerAdapter
FocusAdapter
KeyAdapter
MouseAdapter
MouseMotionAdapter
WindowAdapter

Your Listener or Adapter will receive an event when triggered. These events may be one of the following standard types:

ActionEvent
AdjustmentEvent
ComponentEvent
ContainerEvent
FocusEvent
InputEvent
ItemEvent
KeyEvent
MouseEvent
PaintEvent
TextEvent
WindowEvent

The new event model appears more complex than it actually is. Those of you familiar with many of the frameworks or message-based event models will have a leg up on those who are used to the standard MacOS event loop. Just remember, a Listener is the code that will be triggered by the event (the code that says "I want keystrokes"), and an Event object is a bit of state referring to a specific occurrence of the event (a notification the user pressed 'a'). For our purposes, an adapter is a programmer's aid for implementing a Listener.

Where's my IDL?

Those of you familiar with other mechanisms such as SOM may have noticed the lack of any sort of interface definition files. Simply writing public boolean isAsleep(); is certainly a lot easier than writing SOM idl files, or trying to write COM interfaces by hand. Compiler vendors have made stabs at trying to solve the complexities of SOM and COM with varying degrees of success. Why is this?

C++ libraries are statically compiled code - code which loses most of the type information as it is built. Everything is done as offsets from pointers, with no runtime enforced type checking. For example, any arbitrary pointer can be set and written to - there is no verification that the target of a write is an appropriate location. This is the source of a lot of crashes and memory corruption.

In the original design of Java, all of the type data was kept around in the bytecode. This was originally done to make sure that if an inappropriate cast was made, the runtime would catch the error and throw an exception. C++ added a similar concept called RTTI (runtime type identification) recently, but it doesn't include a lot of the safety checking. As a side effect, it turns out that all of this type information is very handy for parsing the structure of a chunk of code, and made the design of JavaBeans a lot cleaner and more elegant than previous technologies.

Making Your Own Events

The JDK draws a distinction between "low-level" events, such as a mouse down or a mouse moved, and a "semantic" event, such as an action event which is generated by a button press. It is possible for JavaBeans to define their own semantic, higher level events.

Create your own Listener class by implementing an EventListener, and your new event types by implementing an EventObject. Then use the following methods to register your interest in the events, and use the methods above to handle the events:

public void add<EventListenerType>(<EventListenerType> a)
public void remove<EventListenerType(<EventListenerType> a)

It is worth spending some time to carefully plan how you will use these new events, and by adhering to design patterns such as

void <eventOccurenceMethodName>
      (<EventStateObjectType> evt);

You can allow visual builder tools to take advantage of your new event type. An example of this would be

public class ControlEvent extends java.util.EventObject {
	// this event might have an additional method,
	// such as a getValue() if it were a scrollbar 
} 

interface ControlListener extends java.util.EventListener {
	void controlFired(ControlEvent ce);
	void controlDeactivated(ControlEvent ce);
	// these are the methods to be implemented
	// by code interested in the ControlEvent
}

Dive into the JDK 1.1 API level documentation for the new event APIs. As of this writing, you'll have to get your hands dirty by playing with the html documentation directly from JavaSoft.

Final Notes

All public methods may theoretically be exposed to the builder tool. Properties and events which make use of the guidelines above can typically take advantage of the standard tools available to the builder tool (such as standard popups for selecting booleans in the Properties palette, automatically generated Font menus, color pickers, etc.). A suite of well designed components allows you to tie an awful lot of functionality together extremely rapidly; by creating your own you make it much easier for others to leverage your work. There was an awful lot of material of interest to JavaBeans developers we didn't cover here, including Serialization (persistent objects), RMI, and more. Despite the emphasis on visual builder tools, JavaBeans are completely usable directly from a "traditional" environment with handwritten source code.

This article covered the initial concepts of JavaBeans, including the notions of properties and events, and it covered the structure behind how basic JavaBeans are built. Hopefully this is enough for you to get started, and enough for you to understand a bit more about what's going on "under the hood" with JavaBeans. Start off by playing around with Visual Cafe or another JavaBeans visual tool, and once you get a feel for how it works, try making your own JavaBean by taking advantage of the design patterns and property definitions. Once you've gotten a feel for how this works, try playing around with the new event model, defining your own events and understanding how the firing chain of an event works.

Good luck, and I hope JavaBeans helps make writing (and using) code that much easier.

 
AAPL
$103.30
Apple Inc.
+0.80
MSFT
$45.09
Microsoft Corpora
-0.34
GOOG
$577.33
Google Inc.
+5.73

MacTech Search:
Community Search:

Software Updates via MacUpdate

TextSoap 7.4.0 - Flexible text editing u...
TextSoap is for people who work with text. TextSoap effortlessly cleans up text from endlessly different formats. Wash away unwanted characters, spaces, tabs. Fix paragraphs with hard returns at the... Read more
NetShade 6.0.2 - Browse privately using...
NetShade is an Internet security tool that conceals your IP address on the web. NetShade routes your Web connection through either a public anonymous proxy server, or one of NetShade's own dedicated... Read more
Mac DVDRipper Pro 5.0 - Copy, backup, an...
Mac DVDRipper Pro is the DVD backup solution that lets you protect your DVDs from scratches, save your batteries by reading your movies from your hard disk, manage your collection with just a few... Read more
pwSafe 3.1 - Secure password management...
pwSafe provides simple and secure password management across devices and computers. pwSafe uses iCloud to keep your password databases backed-up and synced between Macs and iOS devices. It is... Read more
StatsBar 1.8 - Monitor system processes...
StatsBar gives you a comprehensive and detailed analysis of the following areas of your Mac: CPU usage Memory usage Disk usage Network and bandwidth usage Battery power and health (MacBooks only)... Read more
Path Finder 6.5.5 - Powerful, award-winn...
Path Finder is a file browser that combines the familiar Finder interface with the powerful utilities and innovative features. Just a small selection of the Path Finder 6 feature set: Dual pane... Read more
QuarkXPress 10.2.1 - Desktop publishing...
With QuarkXPress, you can communicate in all the ways you need to -- and always look professional -- in print and digital media, all in a single tool. Features include: Easy to Use -- QuarkXPress is... Read more
Skype 6.19.0.450 - Voice-over-internet p...
Skype allows you to talk to friends, family and co-workers across the Internet without the inconvenience of long distance telephone charges. Using peer-to-peer data transmission technology, Skype... Read more
VueScan 9.4.41 - Scanner software with a...
VueScan is a scanning program that works with most high-quality flatbed and film scanners to produce scans that have excellent color fidelity and color balance. VueScan is easy to use, and has... Read more
Cloud 3.0.0 - File sharing from your men...
Cloud is simple file sharing for the Mac. Drag a file from your Mac to the CloudApp icon in the menubar and we take care of the rest. A link to the file will automatically be copied to your clipboard... Read more

Latest Forum Discussions

See All

Modern Combat 5 Gets a Major Multiplayer...
Modern Combat 5 Gets a Major Multiplayer Update Posted by Jessica Fisher on September 2nd, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Alien Creeps TD Review
Alien Creeps TD Review By Jennifer Allen on September 2nd, 2014 Our Rating: :: EXPENSIVE DEFENSESUniversal App - Designed for iPhone and iPad Alien Creeps TD would be a fun if unremarkable Tower Defense game, but its heavy focus on... | Read more »
The Journey Down: Chapter Two Review
The Journey Down: Chapter Two Review By Jennifer Allen on September 2nd, 2014 Our Rating: :: DARK YET ENTICINGUniversal App - Designed for iPhone and iPad It’s a little dark, in every sense of the word, but The Journey Down:... | Read more »
Function Space, a Social Network App for...
Function Space, a Social Network App for Science, Launches on iOS Posted by Ellis Spice on September 2nd, 2014 [ permalink ] | Read more »
Stupidfast – How Taylor Martinez Switche...
How do you make an Endless Running game more than just another Endless Running game? By adding real life prizes to it, of course! That’s the thinking behind StupidFast: a game designed for football enthusiasts, and the brainchild of former college... | Read more »
Little Raiders: Robin’s Revenge Review
Little Raiders: Robin’s Revenge Review By Jennifer Allen on September 2nd, 2014 Our Rating: :: CASUAL RAIDINGUniversal App - Designed for iPhone and iPad Combining simple combat with village building is a potent combination for... | Read more »
Treasure Tombs: Ra Deal Coming from Bulk...
Treasure Tombs: Ra Deal Coming from Bulkypix and Dark Tonic This Fall Posted by Jessica Fisher on September 2nd, 2014 [ permalink ] Dark Tonic and | Read more »
Pirate Bash Review
Pirate Bash Review By Nadia Oxford on September 2nd, 2014 Our Rating: :: BAD PIRATES, GOOD TIMESUniversal App - Designed for iPhone and iPad Pirate Bash’s turn-based battles add an intriguing twist to a typical physics game.   | Read more »
Tiny Tower Vegas Review
Tiny Tower Vegas Review By Jennifer Allen on September 2nd, 2014 Our Rating: :: STEADY DEVELOPMENTUniversal App - Designed for iPhone and iPad Build a huge tower again but Vegas-style in Tiny Tower Vegas.   | Read more »
The Manhattan Project Review
The Manhattan Project Review By Andrew Fisher on September 2nd, 2014 Our Rating: :: ROCKET SCIENCEUniversal App - Designed for iPhone and iPad The Manhattan Project offers a great Euro-style gameplay experience, but it is totally... | Read more »

Price Scanner via MacPrices.net

Apple refurbished iPads available for up to $...
Apple is offering Certified Refurbished iPad Airs for up to $140 off MSRP. Apple’s one-year warranty is included with each model, and shipping is free. Stock tends to come and go with some of these... Read more
Are We Now In The Post-Post-PC Era?
A longtime and thoroughgoing laptop aficionado, I was more than a little dismayed by Steve Jobs’s declaration back in 2010 when he sprang the iPad on an unsuspecting world. that we’d entered a “post-... Read more
PC Outlook Improves, But 2014 Shipments Still...
According to the International Data Corporation (IDC) Worldwide Quarterly PC Tracker, worldwide PC shipments are expected to fall by -3.7 percent in 2014. To hat’s actually an improvement from the... Read more
IDC Lowers Tablet Sales Projections for 2014...
Following a second consecutive quarter of softer than expected demand, International Data Corporation (IDC) has lowered its worldwide tablet plus 2-in-1 forecast for 2014 to 233.1 million units. The... Read more
Apple now offering refurbished 21-inch 1.4GHz...
The Apple Store is now offering Apple Certified Refurbished 21″ 1.4GHz iMacs for $929 including free shipping plus Apple’s standard one-year warranty. Their price is $170 off the cost of new models,... Read more
Save $50 on the 2.5GHz Mac mini, on sale for...
B&H Photo has the 2.5GHz Mac mini on sale for $549.99 including free shipping. That’s $50 off MSRP, and B&H will also include a free copy of Parallels Desktop software. NY sales tax only. Read more
Save up to $300 on an iMac with Apple refurbi...
The Apple Store has Apple Certified Refurbished iMacs available for up to $300 off the cost of new models. Apple’s one-year warranty is standard, and shipping is free. These are the best prices on... Read more
The Rise of Phablets
Carlisle & Gallagher Consulting Group, a businesses and technology consulting firm focused solely on the financial services industry, has released an infographic depicting the convergence of... Read more
Bad Driver Database App Allows Good Drivers t...
Bad Driver Database 1.4 by Facile Group is a new iOS and Android app that lets users instantly input and see how many times a careless, reckless or just plain stupid driver has been added to the... Read more
Eddy – Cloud Music Player for iPhone/iPad Fre...
Ukraine based CapableBits announces the release of Eddy, its tiny, but smart and powerful cloud music player for iPhone and iPad that allows users to stream or download music directly from cloud... Read more

Jobs Board

*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
Senior Event Manager, *Apple* Retail Market...
…This senior level position is responsible for leading and imagining the Apple Retail Team's global event strategy. Delivering an overarching brand story; in-store, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.