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.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.