TweetFollow Us on Twitter

Growing Java Beans

Volume Number: 14 (1998)
Issue Number: 9
Column Tag: JavaTech

Growing Java Beans

by Andrew Downs
Edited by the MacTech Editorial Staff

A code-based intro to Java's component architecture

Introduction

JavaBeans is the Java component architecture. This article discusses and demonstrates how to write several simple components (hereafter referred to as Beans). The reader should have a general familiarity with Java. The code in this article was developed using the Apple Mac OS Runtime for Java (MRJ) version 2.0 and the MRJ SDK 2.0.1 ea2.

For additional background information, several related articles previously published in MacTech are listed in the reference section at the end of this article. Several books are also listed.

Overview

A Java Bean bears a strong resemblance to a well-written Java application. But since it is a component, a Bean's scope is usually smaller than that of an entire application, making it easier to develop.

Here is a partial list of Bean characteristics. Beans should:

  • expose accessor methods (e.g. getValue() and setValue()) to allow retrieval and changing of attribute values by external sources;
  • allow for easy mixing and matching via GUI development tools;
  • generate or respond to appropriate events;
  • save their state using the Java Serialization mechanism.

In this article, we will explore the code behind two relatively simple Beans. They contain enough of the above-listed features to make them interesting, while remaining easy to read and understand. One of the Beans displays a sequence of lights similar to a U.S.-style traffic light. The other Bean changes the sequence of the light display. We will look at the code for these classes later.

Figure 1 shows the two Beans running within a Java Frame object. (A Frame is a platform-specific window.) Figure 2 shows the Beans running inside the BeanBox, a GUI tool from JavaSoftthat allows you to instantiate, connect, and test Bean behavior. The BeanBox is provided free of charge from JavaSoft, as part of the Beans Development Kit (BDK). Since it is written in Java, the BeanBox can be installed on the Macintosh using the MRJ Software Development Kit tools. It can then be run the same as other Java applications. The URL for obtaining the BeanBox is provided at the end of this article. (Note: you will need a file-extraction program that can open .zip files in order to unpack the BeanBox.)

Figure 1. The finished product running in its own container (a Frame).

Figure 2. Running inside the BeanBox.

Notice that there is little difference in the visible display of the Beans, whether running standalone or in the BeanBox. One Bean appears as a Java Choice menu (a Mac OS popup menu), and the other is a rectangle containing three circles, one of which is filled at any given time.

There are four classes that comprise this project:

  • Global: values shared by the other classes.
  • ModeSelector: a Choice (popup) menu, which specifies the mode of operation: in "normal" mode the lights flash in sequence (green - yellow - red), and in "maintenance" mode only the yellow light flashes.
  • Display: the component which draws the lights. Display also runs a Thread which adds timing capability to its operation.
  • DisplayFrame: a container for the Display and ModeSelector Beans.

We will cover each of these classes in sequence.

Global Values

This class defines some global values that are shared between the Display and ModeSelector classes. These values are collected in one place to simplify housekeeping and maintenance. We will refer to them from the other classes as Global.NORMAL, Global.sleep, etc. This is the Java syntax for referencing static (class) attributes. Note that final means the values cannot be changed after they are initially assigned, so these are constants.

Listing 1: Global.java

Global.java
// Shared values.

public class Global {
       // Mode values; all-caps to set them off from Strings of same name.
   public static final int NORMAL = 0, MAINT = 1;

       // Number of milliseconds for Thread to sleep.
   public static final int sleep = 250;

       // Choice menu item values.
   public static final String normal = "Normal";
   public static final String maint = "Maintenance";
}

Choice Bean

The ModeSelector Bean is a Choice menu component (a popup menu on the Mac). When the user changes the currently selected item, the Bean notifies any registered listeners. (We will see that the DisplayFrame class instantiates a Display object and registers it as a listener on a ModeSelector object.)

Listing 2: ModeSelector.java

ModeSelector.java
// A Choice menu class for changing the display mode (and resulting light sequence).

// Make available the following packages and classes:
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.io.Serializable;
import java.util.Vector;

ModeSelector specifies that it implements the ItemListener interface so that it can receive item changed events (generated when the user makes a selection). The method that must be defined for the ItemListener interface is itemStateChanged(). In this implementation, ModeSelector ignores the event object contents, and checks its own state instead.

public class ModeSelector extends Choice implements 
   ItemListener, Serializable {

       // Mode value.
   private int mode = Global.NORMAL;

       // Keep track of other objects that want to be informed of changes.
   private PropertyChangeSupport changeListeners = 
      new PropertyChangeSupport( this );

   public ModeSelector() {
              // Call the superclass constructor.
      super();

              // Only two items in this menu.
      this.add( Global.normal );
      this.add( Global.maint );

              // Starting mode.
      this.setMode( Global.NORMAL );

              // Listen for selections on ourself.
      this.addItemListener( ( ItemListener )this );
   }

ModeSelector uses its own accessor methods to get and set the mode value. This may seem like overkill, since a class can access its own variables (even private ones, such as mode) directly. However, it is arguably a good habit, since variable references from outside the class should go through accessor methods, and never directly access variable values.

   public int getMode() {
              // Simple accessor function.
      return this.mode;
   }

   public void setMode( int i ) {
              // More complex accessor function.
              // Store the current mode.
      int old = this.getMode();

              // Set the current mode.
      if ( i == Global.NORMAL )
         this.mode = Global.NORMAL;
      else
         this.mode = Global.MAINT;

              // Notify our customers of the change.
      this.changeListeners.firePropertyChange( "mode", 
         new Integer( old ), new Integer( this.getMode() ) );
   }

   public void itemStateChanged( ItemEvent evt ) {
              // If the selected item has actually changed, then change
              // the mode accordingly.
      if ( ( this.getSelectedIndex() == Global.NORMAL ) 
         && ( this.getMode() == Global.MAINT ) )
         this.setMode( Global.NORMAL );
      else if ( ( this.getSelectedIndex() == Global.MAINT )
         && ( this.getMode() == Global.NORMAL ) )
         this.setMode( Global.MAINT );
   }

   public void addPropertyChangeListener( 
      PropertyChangeListener l ) {
              // Add someone else as a customer.
      changeListeners.addPropertyChangeListener( l );
   }

   public void removePropertyChangeListener( 
      PropertyChangeListener l ) {
              // Remove a customer.
      changeListeners.removePropertyChangeListener( l );
   }
}

Note that ModeSelector does not define any unique serialization that needs to occur. Instead, it uses the superclass' implementation.

Center of Attention

This Bean defines the lights that will be drawn as part of the traffic light. It also contains a Thread which is used to time the repaints.

Note that Display inherits directly from java.awt.Component. This makes it a "lightweight" component (as well as a Bean), which simply means that it has no native window object associated with it at runtime, and also none of the overhead associated with such an object.

Listing 3: Display.java

Display.java
// The traffic light class, which sequences and draws the colored lights.

import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.io.*;
import java.util.*;

public class Display extends Component implements 
   PropertyChangeListener, ItemListener, Serializable, 
   Runnable {

       // Size matters.
   private int width = 50, height = 165;

       // count = number of seconds.
       // mode determines display pattern.
       // interval = number of milliseconds for Thread to sleep. 
   private int count = 0, mode = Global.MAINT, interval = 
      Global.sleep;

       // color becomes important in NORMAL mode.
   private Color color;

       // Thread is not Serializable.
   transient private Thread runner;

   public Display() {
              // Call the superclass constructor.
      super();

              // We know how big we want to be.
      this.setSize( this.getPreferredSize() );

              // Set some instance variables.
      this.setMode( Global.NORMAL );
      this.setColor( Color.red );

              // Create and start a Thread.
      runner = new Thread( this );
      runner.start();
   }

The runner object used in this class, in conjunction with the Runnable interface, allows Display to take on the behavior of a Thread without actually subclassing directly from Thread. In the run() method, the runner is put to sleep temporarily. On wakeup, it compares the current time to the reference time, and if the reference time has been exceeded, this object's state gets updated (i.e. the light color may change).

   public void run() {
              // Reference point will be current time plus 1 second.
      Calendar triggerTime = Calendar.getInstance();
      triggerTime.add( Calendar.SECOND, 1 );

      while ( true ) {

         try {
                            // Sleep for <interval> milliseconds.
            Thread.sleep( this.interval );
         }
         catch ( InterruptedException ex ) {
            System.out.println( "InterruptedException..." );
         }

                      // Compare the current time to the reference point.
         if ( Calendar.getInstance().after( triggerTime ) ) {
                            // Take action.
            this.timerExpired();

                            // Reset the reference point.
            triggerTime = Calendar.getInstance();
            triggerTime.add( Calendar.SECOND, 1 );
         }
      }
   }

Overriding the getPreferredSize() method (whose original definition is in java.awt.Component) enables us to specify the desired size (in pixels) of this object. Notice that the preferred size will also be the minimum size. If we do not override these methods, some containers (such as the BeanBox) will not automatically size the object so that the lights are visible.

   public Dimension getPreferredSize() {
              // When queried, we know how big we *want* to be.
      return new Dimension( this.width, this.height );
   }

   public Dimension getMinimumSize() {
              // Our preferred size is already the minimum size.
      return this.getPreferredSize();
   }

The itemStateChanged() method allows this component to be dynamically connected to a source of ItemEvents, such as the ModeSelector class. Without it, you must directly bind the "mode" property of both classes in order to see a state change while running in the BeanBox.

   public void itemStateChanged( ItemEvent evt ) {
              // If the selected item has actually changed, 
              // then change the mode accordingly.
              // This is the same method as in ModeSelector.java.
              // Here, it allows this Component to receive changes directly,
              // and get hooked up in the BeanBox.
      if ( evt.getItem().toString().equals( Global.normal ) 
         && this.getMode() == Global.MAINT ) {
         this.setMode( Global.NORMAL );
         this.reset();
      }
      else if 
         ( evt.getItem().toString().equals( Global.maint ) 
         && this.getMode() == Global.NORMAL ) {
         this.setMode( Global.MAINT );
         this.reset();
      }
   }

The following method gets called from run() approximately every second. The timing used here is simple: in normal mode, each light will be "on" for five seconds; in maintenance mode, that interval is reduced to one second. In terms of color, normal mode sequences the lights (green, then yellow, then red), while maintenance mode only flashes the yellow light.

   public void timerExpired() {
              // count is the number of elapsed seconds.
      this.count++;

      if ( this.getMode() == Global.NORMAL ) {
                     // In normal mode, each light stays on for 5 seconds.
         if ( this.count > 4 ) {
            this.count = 0;

                            // Cycle through the light sequence.
            if ( this.getColor() == Color.red )
               this.setColor( Color.green );
            else if ( this.getColor() == Color.yellow )
               this.setColor( Color.red );
            else
               this.setColor( Color.yellow );

            repaint();
         }
      }
      else if ( mode == Global.MAINT ) {
                     // In maintenance mode, the light stays on for 1 second.
         if ( this.count > 0 ) {
            this.count = 0;

                            // Alternate yellow and black.
            if ( this.getColor() == Color.yellow )
               this.setColor( Color.black );
            else
               this.setColor( Color.yellow );

            repaint();
         }
      }
   }

   public void paint( Graphics g ) {
              // Draw the background.
      g.setColor( Color.lightGray );
      g.fillRect( 0, 0, 50, 165 );

      if ( this.getMode() == Global.NORMAL ) {
                     // For any light, black signifies "off".
         g.setColor( Color.black );

                     // Handle the red light.
         if ( this.getColor() == Color.red )
            g.setColor( this.getColor() );
         g.fillOval( 5, 10, 40, 40 );

                     // Handle the yellow light.
         if ( this.getColor() == Color.yellow )
            g.setColor( this.getColor() );
         else
            g.setColor( Color.black );
         g.fillOval( 5, 60, 40, 40 );

                     // Handle the green light.
         if ( this.getColor() == Color.green )
            g.setColor( this.getColor() );
         else
            g.setColor( Color.black );
         g.fillOval( 5, 110, 40, 40 );
      }
      else if ( this.getMode() == Global.MAINT ) {
                     // Red light is always "off".
         g.setColor( Color.black );
         g.fillOval( 5, 10, 40, 40 );

                     // Yellow light may be "on".
         if ( this.getColor() == Color.yellow )
            g.setColor( this.getColor() );
         g.fillOval( 5, 60, 40, 40 );

                     // Green light is always "off".
         g.setColor( Color.black );
         g.fillOval( 5, 110, 40, 40 );
      }
   }

       // Four simple accessor methods.
   public Color getColor() {
      return this.color;
   }

   public void setColor( Color c ) {
      this.color = c;
   }

   public int getMode() {
      return mode;
   }

   public void setMode( int i ) {
      mode = i;
   }

   public void propertyChange( PropertyChangeEvent evt ) {
              // This is how we get notified of a property change.
              // Make ints out of the old and new values...
      Integer theOldInt = ( Integer )( evt.getOldValue() );
      Integer theNewInt = ( Integer )( evt.getNewValue() );

              // ...then compare them. Any change is acceptable.
      if ( theNewInt.intValue() != theOldInt.intValue() ) {
         mode = theNewInt.intValue();
         this.reset();
      }
   }

   private void reset() {
              // In several cases, we need a way to force the lights 
              // to a known starting point.
      this.setColor( Color.yellow );
      this.count = 5;
      this.repaint();
   }

When retrieving the object's state, the runner object must be created from scratch, since the Thread class is not serializable.

   private void readObject( ObjectInputStream s ) throws 
      ClassNotFoundException, IOException {
              // Always call the default read method.
      s.defaultReadObject();

              // Since the Thread cannot be saved, create a new one after
              // startup and state retrieval.
      runner = new Thread( this );
      runner.start();
   }
}

Container App

The DisplayFrame class is provided as a container app for the other Beans we've built. It is a Frame containing the Display (traffic light) and ModeSelector. Figure 1 shows the Beans running inside a DisplayFrame object. Since DisplayFrame is an application, it can run independently of the BeanBox.

Listing 4: DisplayFrame.java

DisplayFrame.java
// A container app for runtime.

import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.io.*;
import java.util.*;

public class DisplayFrame extends Frame implements 
   Serializable {
       // Frame size.
   int width = 125, height = 185;

   public static void main( String args[] ) {
              // This class can be run outside of the BeanBox.
      DisplayFrame df = new DisplayFrame();
   }

   public DisplayFrame() {
              // Call the superclass constructor.
      super();

              // We know how big we want to be.
      this.setSize( this.width, this.height );

              // Create the traffic light...
      Display display = new Display();

              // ...and the choice menu.
      ModeSelector ms = new ModeSelector();

Add the Display object as a listener on the ModeSelector, so that it will be notified when the "mode" value changes.

      ms.addPropertyChangeListener( 
         ( PropertyChangeListener )display );

              // Setup the display area.
      Panel p = new Panel();
      p.setLayout( new BorderLayout() );
      p.add( "Center", display );
      p.add( "South", ms );

      this.add( p );
      this.setVisible( true );
   }

   public Dimension getPreferredSize() {
              // When queried, we know how big we *want* to be.
      return new Dimension( this.width, this.height );
   }

   public Dimension getMinimumSize() {
              // Our preferred size is already the minimum size.
      return this.getPreferredSize();
   }

   private void readObject( ObjectInputStream s ) throws 
      ClassNotFoundException, IOException {
              // Always call the default read method.
      s.defaultReadObject();
   }
}

Compiling and Running

You can compile the .java (source) files using the javac (Java compiler) tool included in the MRJ SDK Tools folder, or using the Java compiler in CodeWarrior or Visual Cafe. You can then optionally create a .jar (Java ARchive) file containing the resulting .class (output) files.

The archive for this article includes the .java and .class files (in separate directories), and individual .jar files containing each Bean and Global.class. In addition, the manifest directory contains manifest files for each of the classes, for use in building JAR files. You can also combine the manifests and classes into one big JAR file.

To run the program, drag the file DisplayFrame.class onto the JBindery application icon, which is located in the MRJ SDK JBindery folder. Once JBindery launches, it will display "DisplayFrame" in the class name field. (This field specifies the name of the class to run at application startup; that class must contain a main() method.) Click OK to run the program. To run inside the BeanBox, add the .jar files to the jars directory on your hard drive. Then, launch the BeanBox application. It should open and read the .jar files, and display the Beans in the palette on the left side. It will write an error message to the console stating that Global.jar does not contain any Beans. This is not a problem, since we know that Global is not a Bean, but rather a supporting class.

Conclusion

Java Beans should be reusable, customizable, and packaged in JAR files. As Bean development tools become more widespread, developers will find it even easier to create custom apps by combining Beans in new ways. Bean development allows an incremental, flexible approach which should make it easy for all developers to participate.

References

  • Developing Java Beans, Robert Englander, O'Reilly & Associates, Inc., 1997.
  • Java in a Nutshell, David Flanagan, O'Reilly & Associates, Inc., 1997.
  • Exploring Java, Patrick Niemeyer and Joshua Peck, O'Reilly & Associates, Inc., 1997.
  • Java Serialization, Andrew Downs, MacTech Magazine, April 1998.
  • Building Beans, Will Iverson, MacTech Magazine, June 1997.

URLs


Andrew Downs is a Senior Software Engineer for Template Software in New Orleans, LA, designing and building enterprise apps. He's trying to teach his twin sons that mice are for pointing, not eating. Andrew wrote the Macintosh freeware program Recent Additions, and the Java application UDPing. You can reach him at andrew@nola.template.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Whitethorn Games combines two completely...
If you have ever gone fishing then you know that it is a lesson in patience, sitting around waiting for a bite that may never come. Well, that's because you have been doing it wrong, since as Whitehorn Games now demonstrates in new release Skate... | Read more »
Call of Duty Warzone is a Waiting Simula...
It's always fun when a splashy multiplayer game comes to mobile because they are few and far between, so I was excited to see the notification about Call of Duty: Warzone Mobile (finally) launching last week and wanted to try it out. As someone who... | Read more »
Albion Online introduces some massive ne...
Sandbox Interactive has announced an upcoming update to its flagship MMORPG Albion Online, containing massive updates to its existing guild Vs guild systems. Someone clearly rewatched the Helms Deep battle in Lord of the Rings and spent the next... | Read more »
Chucklefish announces launch date of the...
Chucklefish, the indie London-based team we probably all know from developing Terraria or their stint publishing Stardew Valley, has revealed the mobile release date for roguelike deck-builder Wildfrost. Developed by Gaziter and Deadpan Games, the... | Read more »
Netmarble opens pre-registration for act...
It has been close to three years since Netmarble announced they would be adapting the smash series Solo Leveling into a video game, and at last, they have announced the opening of pre-orders for Solo Leveling: Arise. [Read more] | Read more »
PUBG Mobile celebrates sixth anniversary...
For the past six years, PUBG Mobile has been one of the most popular shooters you can play in the palm of your hand, and Krafton is celebrating this milestone and many years of ups by teaming up with hit music man JVKE to create a special song for... | Read more »
ASTRA: Knights of Veda refuse to pump th...
In perhaps the most recent example of being incredibly eager, ASTRA: Knights of Veda has dropped its second collaboration with South Korean boyband Seventeen, named so as it consists of exactly thirteen members and a video collaboration with Lee... | Read more »
Collect all your cats and caterpillars a...
If you are growing tired of trying to build a town with your phone by using it as a tiny, ineffectual shover then fear no longer, as Independent Arts Software has announced the upcoming release of Construction Simulator 4, from the critically... | Read more »
Backbone complete its lineup of 2nd Gene...
With all the ports of big AAA games that have been coming to mobile, it is becoming more convenient than ever to own a good controller, and to help with this Backbone has announced the completion of their 2nd generation product lineup with their... | Read more »
Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »

Price Scanner via MacPrices.net

B&H has Apple’s 13-inch M2 MacBook Airs o...
B&H Photo has 13″ MacBook Airs with M2 CPUs and 256GB of storage in stock and on sale for up to $150 off Apple’s new MSRP, starting at only $849. Free 1-2 day delivery is available to most US... Read more
M2 Mac minis on sale for $100-$200 off MSRP,...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100-$200 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $... Read more
Mac Studios with M2 Max and M2 Ultra CPUs on...
B&H Photo has standard-configuration Mac Studios with Apple’s M2 Max & Ultra CPUs in stock today and on Easter sale for $200 off MSRP. Their prices are the lowest available for these models... Read more
Deal Alert! B&H Photo has Apple’s 14-inch...
B&H Photo has new Gray and Black 14″ M3, M3 Pro, and M3 Max MacBook Pros on sale for $200-$300 off MSRP, starting at only $1399. B&H offers free 1-2 day delivery to most US addresses: – 14″ 8... Read more
Department Of Justice Sets Sights On Apple In...
NEWS – The ball has finally dropped on the big Apple. The ball (metaphorically speaking) — an antitrust lawsuit filed in the U.S. on March 21 by the Department of Justice (DOJ) — came down following... Read more
New 13-inch M3 MacBook Air on sale for $999,...
Amazon has Apple’s new 13″ M3 MacBook Air on sale for $100 off MSRP for the first time, now just $999 shipped. Shipping is free: – 13″ MacBook Air (8GB RAM/256GB SSD/Space Gray): $999 $100 off MSRP... Read more
Amazon has Apple’s 9th-generation WiFi iPads...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Discounted 14-inch M3 MacBook Pros with 16GB...
Apple retailer Expercom has 14″ MacBook Pros with M3 CPUs and 16GB of standard memory discounted by up to $120 off Apple’s MSRP: – 14″ M3 MacBook Pro (16GB RAM/256GB SSD): $1691.06 $108 off MSRP – 14... Read more
Clearance 15-inch M2 MacBook Airs on sale for...
B&H Photo has Apple’s 15″ MacBook Airs with M2 CPUs (8GB RAM/256GB SSD) in stock today and on clearance sale for $999 in all four colors. Free 1-2 delivery is available to most US addresses.... Read more
Clearance 13-inch M1 MacBook Airs drop to onl...
B&H has Apple’s base 13″ M1 MacBook Air (Space Gray, Silver, & Gold) in stock and on clearance sale today for $300 off MSRP, only $699. Free 1-2 day shipping is available to most addresses in... Read more

Jobs Board

Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply 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
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
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
Business Analyst | *Apple* Pay - Banco Popu...
Business Analyst | Apple PayApply now " Apply now + Apply Now + Start applying with LinkedIn Start + Please wait Date:Mar 19, 2024 Location: San Juan-Cupey, PR Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.