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 Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links... | Read more »
Price of Glory unleashes its 1.4 Alpha u...
As much as we all probably dislike Maths as a subject, we do have to hand it to geometry for giving us the good old Hexgrid, home of some of the best strategy games. One such example, Price of Glory, has dropped its 1.4 Alpha update, stocked full... | Read more »
The SLC 2025 kicks off this month to cro...
Ever since the Solo Leveling: Arise Championship 2025 was announced, I have been looking forward to it. The promotional clip they released a month or two back showed crowds going absolutely nuts for the previous competitions, so imagine the... | Read more »
Dive into some early Magicpunk fun as Cr...
Excellent news for fans of steampunk and magic; the Precursor Test for Magicpunk MMORPG Crystal of Atlan opens today. This rather fancy way of saying beta test will remain open until March 5th and is available for PC - boo - and Android devices -... | Read more »
Prepare to get your mind melted as Evang...
If you are a fan of sci-fi shooters and incredibly weird, mind-bending anime series, then you are in for a treat, as Goddess of Victory: Nikke is gearing up for its second collaboration with Evangelion. We were also treated to an upcoming... | Read more »
Square Enix gives with one hand and slap...
We have something of a mixed bag coming over from Square Enix HQ today. Two of their mobile games are revelling in life with new events keeping them alive, whilst another has been thrown onto the ever-growing discard pile Square is building. I... | Read more »
Let the world burn as you have some fest...
It is time to leave the world burning once again as you take a much-needed break from that whole “hero” lark and enjoy some celebrations in Genshin Impact. Version 5.4, Moonlight Amidst Dreams, will see you in Inazuma to attend the Mikawa Flower... | Read more »
Full Moon Over the Abyssal Sea lands on...
Aether Gazer has announced its latest major update, and it is one of the loveliest event names I have ever heard. Full Moon Over the Abyssal Sea is an amazing name, and it comes loaded with two side stories, a new S-grade Modifier, and some fancy... | Read more »
Open your own eatery for all the forest...
Very important question; when you read the title Zoo Restaurant, do you also immediately think of running a restaurant in which you cook Zoo animals as the course? I will just assume yes. Anyway, come June 23rd we will all be able to start up our... | Read more »
Crystal of Atlan opens registration for...
Nuverse was prominently featured in the last month for all the wrong reasons with the USA TikTok debacle, but now it is putting all that behind it and preparing for the Crystal of Atlan beta test. Taking place between February 18th and March 5th,... | Read more »

Price Scanner via MacPrices.net

AT&T is offering a 65% discount on the ne...
AT&T is offering the new iPhone 16e for up to 65% off their monthly finance fee with 36-months of service. No trade-in is required. Discount is applied via monthly bill credits over the 36 month... Read more
Use this code to get a free iPhone 13 at Visi...
For a limited time, use code SWEETDEAL to get a free 128GB iPhone 13 Visible, Verizon’s low-cost wireless cell service, Visible. Deal is valid when you purchase the Visible+ annual plan. Free... Read more
M4 Mac minis on sale for $50-$80 off MSRP at...
B&H Photo has M4 Mac minis in stock and on sale right now for $50 to $80 off Apple’s MSRP, each including free 1-2 day shipping to most US addresses: – M4 Mac mini (16GB/256GB): $549, $50 off... Read more
Buy an iPhone 16 at Boost Mobile and get one...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering one year of free Unlimited service with the purchase of any iPhone 16. Purchase the iPhone at standard MSRP, and then choose... Read more
Get an iPhone 15 for only $299 at Boost Mobil...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering the 128GB iPhone 15 for $299.99 including service with their Unlimited Premium plan (50GB of premium data, $60/month), or $20... Read more
Unreal Mobile is offering $100 off any new iP...
Unreal Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering a $100 discount on any new iPhone with service. This includes new iPhone 16 models as well as iPhone 15, 14, 13, and SE... Read more
Apple drops prices on clearance iPhone 14 mod...
With today’s introduction of the new iPhone 16e, Apple has discontinued the iPhone 14, 14 Pro, and SE. In response, Apple has dropped prices on unlocked, Certified Refurbished, iPhone 14 models to a... Read more
B&H has 16-inch M4 Max MacBook Pros on sa...
B&H Photo is offering a $360-$410 discount on new 16-inch MacBook Pros with M4 Max CPUs right now. B&H offers free 1-2 day shipping to most US addresses: – 16″ M4 Max MacBook Pro (36GB/1TB/... Read more
Amazon is offering a $100 discount on the M4...
Amazon has the M4 Pro Mac mini discounted $100 off MSRP right now. Shipping is free. Their price is the lowest currently available for this popular mini: – Mac mini M4 Pro (24GB/512GB): $1299, $100... Read more
B&H continues to offer $150-$220 discount...
B&H Photo has 14-inch M4 MacBook Pros on sale for $150-$220 off MSRP. B&H offers free 1-2 day shipping to most US addresses: – 14″ M4 MacBook Pro (16GB/512GB): $1449, $150 off MSRP – 14″ M4... Read more

Jobs Board

All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.