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

Top Hat Studios unveils a new gameplay t...
There are a lot of big games coming that you might be excited about, but one of those I am most interested in is Athenian Rhapsody because it looks delightfully silly. The developers behind this project, the rather fancy-sounding Top Hat Studios,... | Read more »
Bound through time on the hunt for sneak...
Have you ever sat down and wondered what would happen if Dr Who and Sherlock Holmes went on an adventure? Well, besides probably being the best mash-up of English fiction, you'd get the Hidden Through Time series, and now Rogueside has announced... | Read more »
The secrets of Penacony might soon come...
Version 2.2 of Honkai: Star Rail is on the horizon and brings the culmination of the Penacony adventure after quite the escalation in the latest story quests. To help you through this new expansion is the introduction of two powerful new... | Read more »
The Legend of Heroes: Trails of Cold Ste...
I adore game series that have connecting lore and stories, which of course means the Legend of Heroes is very dear to me, Trails lore has been building for two decades. Excitedly, the next stage is upon us as Userjoy has announced the upcoming... | Read more »
Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »

Price Scanner via MacPrices.net

Save $300 at Apple on 14-inch M3 MacBook Pros...
Apple has 14″ M3 MacBook Pros with 16GB of RAM, Certified Refurbished, available for $270-$300 off MSRP. Each model features a new outer case, shipping is free, and an Apple 1-year warranty is... Read more
Apple continues to offer 14-inch M3 MacBook P...
Apple has 14″ M3 MacBook Pros, Certified Refurbished, available starting at only $1359 and ranging up to $270 off MSRP. Each model features a new outer case, shipping is free, and an Apple 1-year... Read more
Apple AirPods Pro with USB-C return to all-ti...
Amazon has Apple’s AirPods Pro with USB-C in stock and on sale for $179.99 including free shipping. Their price is $70 (28%) off MSRP, and it’s currently the lowest price available for new AirPods... Read more
Apple Magic Keyboards for iPads are on sale f...
Amazon has Apple Magic Keyboards for iPads on sale today for up to $70 off MSRP, shipping included: – Magic Keyboard for 10th-generation Apple iPad: $199, save $50 – Magic Keyboard for 11″ iPad Pro/... Read more
Apple’s 13-inch M2 MacBook Airs return to rec...
Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices currently... Read more
Best Buy is clearing out iPad Airs for up to...
In advance of next week’s probably release of new and updated iPad Airs, Best Buy has 10.9″ M1 WiFi iPad Airs on record-low sale prices for up to $200 off Apple’s MSRP, starting at $399. Sale prices... Read more
Every version of Apple Pencil is on sale toda...
Best Buy has all Apple Pencils on sale today for $79, ranging up to 39% off MSRP for some models. Sale prices for online orders only, in-store prices may vary. Order online and choose free shipping... Read more
Sunday Sale: Apple Studio Display with Standa...
Amazon has the standard-glass Apple Studio Display on sale for $300 off MSRP for a limited time. Shipping is free: – Studio Display (Standard glass): $1299.97 $300 off MSRP For the latest prices and... Read more
Apple is offering significant discounts on 16...
Apple has a full line of 16″ M3 Pro and M3 Max MacBook Pros available, Certified Refurbished, starting at $2119 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free... Read more
Apple HomePods on sale for $30-$50 off MSRP t...
Best Buy is offering a $30-$50 discount on Apple HomePods this weekend on their online store. The HomePod mini is on sale for $69.99, $30 off MSRP, while Best Buy has the full-size HomePod on sale... Read more

Jobs Board

*Apple* App Developer - Datrose (United Stat...
…year experiencein programming and have computer knowledge with SWIFT. Job Responsibilites: Apple App Developer is expected to support essential tasks for the RxASL Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple 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
*Apple* Software Engineer - HP Inc. (United...
…Mobile, Windows and Mac applications. We are seeking a high energy Senior Apple mobile engineer who can lead and drive application development while also enabling Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.