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

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 »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »

Price Scanner via MacPrices.net

Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more
Updated Apple MacBook Price Trackers
Our Apple award-winning MacBook Price Trackers are continually updated with the latest information on prices, bundles, and availability for 16″ and 14″ MacBook Pros along with 13″ and 15″ MacBook... Read more
Every model of Apple’s 13-inch M3 MacBook Air...
Best Buy has Apple 13″ MacBook Airs with M3 CPUs in stock and on sale today for $100 off MSRP. Prices start at $999. Their prices are the lowest currently available for new 13″ M3 MacBook Airs among... Read more
Sunday Sale: Apple iPad Magic Keyboards for 1...
Walmart has Apple Magic Keyboards for 12.9″ iPad Pros, in Black, on sale for $150 off MSRP on their online store. Sale price for online orders only, in-store price may vary. Order online and choose... Read more
Apple Watch Ultra 2 now available at Apple fo...
Apple has, for the first time, begun offering Certified Refurbished Apple Watch Ultra 2 models in their online store for $679, or $120 off MSRP. Each Watch includes Apple’s standard one-year warranty... Read more
AT&T has the iPhone 14 on sale for only $...
AT&T has the 128GB Apple iPhone 14 available for only $5.99 per month for new and existing customers when you activate unlimited service and use AT&T’s 36 month installment plan. The fine... Read more
Amazon is offering a $100 discount on every M...
Amazon is offering a $100 instant discount on each configuration of Apple’s new 13″ M3 MacBook Air, in Midnight, this weekend. These are the lowest prices currently available for new 13″ M3 MacBook... Read more
You can save $300-$480 on a 14-inch M3 Pro/Ma...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more

Jobs Board

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
IT Systems Engineer ( *Apple* Platforms) - S...
IT Systems Engineer ( Apple Platforms) at SpaceX Hawthorne, CA SpaceX was founded under the belief that a future where humanity is out exploring the stars is Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.