Wednesday 29 March 2017

Combo Boxes, Tabbed Panes & Scroll Panes - Java Tutorials

Combo Boxes

Swing provides a combo box (a combination of a text field and a drop-down list) through the JComboBox class, which extends JComponent. A combo box normally displays one entry. However, it can also display a drop-down list that allows a user to select a different entry. You can also type your selection into the text field. Two of JComboBox’s constructors are shown here:

      JComboBox( )
      JComboBox(Vector v)

Here, v is a vector that initializes the combo box. 

Items are added to the list of choices via the addItem( ) method, whose signature is shown here:

      void addItem(Object obj)

Here, obj is the object to be added to the combo box.

The following example contains a combo box and a label. The label displays an icon. The combo box contains entries for “France”, “Germany”, “Italy”, and “Japan”. When a country is selected, the label is updated to display the flag for that country.

  import java.awt.*;
  import java.awt.event.*;
  import javax.swing.*;
  /*
    <applet code="JComboBoxDemo" width=300 height=100>
    </applet>
  */

  public class JComboBoxDemo extends JApplet
  implements ItemListener {
    JLabel jl;
    ImageIcon france, germany, italy, japan;

    public void init() {

      // Get content pane
      Container contentPane = getContentPane();
      contentPane.setLayout(new FlowLayout());

      // Create a combo box and add it
      // to the panel
      JComboBox jc = new JComboBox();
      jc.addItem("France");
      jc.addItem("Germany");
      jc.addItem("Italy");
      jc.addItem("Japan");
      jc.addItemListener(this);
      contentPane.add(jc);

      // Create label
      jl = new JLabel(new ImageIcon("france.gif"));
      contentPane.add(jl);
    }

    public void itemStateChanged(ItemEvent ie) {
      String s = (String)ie.getItem();
      jl.setIcon(new ImageIcon(s + ".gif"));
    }
  }




Tabbed Panes

A tabbed pane is a component that appears as a group of folders in a file cabinet. Each folder has a title. When a user selects a folder, its contents become visible. Only one of the folders may be selected at a time. Tabbed panes are commonly used for setting configuration options.

Tabbed panes are encapsulated by the JTabbedPane class, which extends JComponent. We will use its default constructor. Tabs are defined via the following method:

      void addTab(String str, Component comp)

Here, str is the title for the tab, and comp is the component that should be added to the tab. Typically, a JPanel or a subclass of it is added.

The general procedure to use a tabbed pane in an applet is outlined here:
  1. Create a JTabbedPane object.
  2. Call addTab( ) to add a tab to the pane. (The arguments to this method define the title of the tab and the component it contains.)
  3. Repeat step 2 for each tab.
  4. Add the tabbed pane to the content pane of the applet.


The following example illustrates how to create a tabbed pane. The first tab is titled “Cities” and contains four buttons. Each button displays the name of a city. The second tab is titled “Colors” and contains three check boxes. Each check box displays the name of a color. The third tab is titled “Flavors” and contains one combo box. This enables the user to select one of three flavors.

  import javax.swing.*;
  /*
    <applet code="JTabbedPaneDemo" width=400 height=100>
    </applet>
  */

  public class JTabbedPaneDemo extends JApplet {

    public void init() {

      JTabbedPane jtp = new JTabbedPane();
      jtp.addTab("Cities", new CitiesPanel());
      jtp.addTab("Colors", new ColorsPanel());
      jtp.addTab("Flavors", new FlavorsPanel());
      getContentPane().add(jtp);
    }
  }

  class CitiesPanel extends JPanel {

    public CitiesPanel() {

      JButton b1 = new JButton("New York");
      add(b1);
      JButton b2 = new JButton("London");
      add(b2);
      JButton b3 = new JButton("Hong Kong");
      add(b3);
      JButton b4 = new JButton("Tokyo");
      add(b4);
    }
  }

  class ColorsPanel extends JPanel {

    public ColorsPanel() {

      JCheckBox cb1 = new JCheckBox("Red");
      add(cb1);
      JCheckBox cb2 = new JCheckBox("Green");
      add(cb2);
      JCheckBox cb3 = new JCheckBox("Blue");
      add(cb3);
    }
  }

  class FlavorsPanel extends JPanel {

    public FlavorsPanel() {

      JComboBox jcb = new JComboBox();
      jcb.addItem("Vanilla");
      jcb.addItem("Chocolate");
      jcb.addItem("Strawberry");
      add(jcb);
    }
  }




Scroll Panes

A scroll pane is a component that presents a rectangular area in which a component may be viewed. Horizontal and/or vertical scroll bars may be provided if necessary. Scroll panes are implemented in Swing by the JScrollPane class, which extends JComponent. Some of its constructors are shown here:

      JScrollPane(Component comp)
      JScrollPane(int vsb, int hsb)
      JScrollPane(Component comp, int vsb, int hsb)

Here, comp is the component to be added to the scroll pane. vsb and hsb are int constants that define when vertical and horizontal scroll bars for this scroll pane are shown. These constants are defined by the ScrollPaneConstants interface. Some examples of these constants are described as follows:

Constant  --  Description

HORIZONTAL_SCROLLBAR_ALWAYS:  Always provide horizontal scroll bar

HORIZONTAL_SCROLLBAR_AS_NEEDED:  Provide horizontal scroll bar, if needed

VERTICAL_SCROLLBAR_ALWAYS:  Always provide vertical scroll bar

VERTICAL_SCROLLBAR_AS_NEEDED:  Provide vertical scroll bar, if needed


Here are the steps that you should follow to use a scroll pane in an applet:
  1. Create a JComponent object.
  2. Create a JScrollPane object. (The arguments to the constructor specify the component and the policies for vertical and horizontal scroll bars.)
  3. Add the scroll pane to the content pane of the applet.


The following example illustrates a scroll pane. First, the content pane of the JApplet object is obtained and a border layout is assigned as its layout manager. Next a JPanel object is created and four hundred buttons are added to it, arranged into twenty columns. The panel is then added to a scroll pane, and the scroll pane is added to the content pane. This causes vertical and horizontal scroll bars to appear. You can use the scroll bars to scroll the buttons into view.

  import java.awt.*;
  import javax.swing.*;
  /*
    <applet code="JScrollPaneDemo" width=300 height=250>
    </applet>
  */

  public class JScrollPaneDemo extends JApplet {

    public void init() {

      // Get content pane
      Container contentPane = getContentPane();
      contentPane.setLayout(new BorderLayout());

      // Add 400 buttons to a panel
      JPanel jp = new JPanel();
      jp.setLayout(new GridLayout(20, 20));
      int b = 0;
      for(int i = 0; i < 20; i++) {
        for(int j = 0; j < 20; j++) {
          jp.add(new JButton("Button " + b));
          ++b;
        }
      }

      // Add panel to a scroll pane
      int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
      int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
      JScrollPane jsp = new JScrollPane(jp, v, h);

      // Add scroll pane to the content pane
      contentPane.add(jsp, BorderLayout.CENTER);
    }
  }

Buttons - Java Tutorials

Swing buttons provide features that are not found in the Button class defined by the AWT. For example, you can associate an icon with a Swing button. Swing buttons are subclasses of the AbstractButton class, which extends JComponent. AbstractButton contains many methods that allow you to control the behavior of buttons, check boxes, and radio buttons. For example, you can define different icons that are displayed for the component when it is disabled, pressed, or selected. Another icon can be used as a rollover icon, which is displayed when the mouse is positioned over that component. The following are the methods that control this behavior:

      void setDisabledIcon(Icon di)
      void setPressedIcon(Icon pi)
      void setSelectedIcon(Icon si)
      void setRolloverIcon(Icon ri)

Here, di, pi, si, and ri are the icons to be used for these different conditions. The text associated with a button can be read and written via the following methods:

      String getText( )
      void setText(String s)

Here, s is the text to be associated with the button. Concrete subclasses of AbstractButton generate action events when they are pressed. Listeners register and unregister for these events via the methods shown here:

      void addActionListener(ActionListener al)
      void removeActionListener(ActionListener al)

Here, al is the action listener. AbstractButton is a superclass for push buttons, check boxes, and radio buttons. Each is examined next.


The JButton Class

The JButton class provides the functionality of a push button. JButton allows an icon, a string, or both to be associated with the push button. Some of its constructors are shown here:

      JButton(Icon i)
      JButton(String s)
      JButton(String s, Icon i)

Here, s and i are the string and icon used for the button. The following example displays four push buttons and a text field. Each button displays an icon that represents the flag of a country. When a button is pressed, the name of that country is displayed in the text field. The applet begins by getting its content pane and setting the layout manager of that pane. Four image buttons are created and added to the content pane. Next, the applet is registered to receive action events that are generated by the buttons. A text field is then created and added to the applet. Finally, a handler for action events displays the command string that is associated with the button. The text field is used to present this string.

  import java.awt.*;
  import java.awt.event.*;
  import javax.swing.*;
  /*
    <applet code="JButtonDemo" width=250 height=300>
    </applet>
  */

  public class JButtonDemo extends JApplet
  implements ActionListener {
    JTextField jtf;

    public void init() {

      // Get content pane
      Container contentPane = getContentPane();
      contentPane.setLayout(new FlowLayout());

      // Add buttons to content pane
      ImageIcon france = new ImageIcon("france.gif");
      JButton jb = new JButton(france);
      jb.setActionCommand("France");
      jb.addActionListener(this);
      contentPane.add(jb);

      ImageIcon germany = new ImageIcon("germany.gif");
      jb = new JButton(germany);
      jb.setActionCommand("Germany");
      jb.addActionListener(this);
      contentPane.add(jb);

      ImageIcon italy = new ImageIcon("italy.gif");
      jb = new JButton(italy);
      jb.setActionCommand("Italy");
      jb.addActionListener(this);
      contentPane.add(jb);

      ImageIcon japan = new ImageIcon("japan.gif");
      jb = new JButton(japan);
      jb.setActionCommand("Japan");
      jb.addActionListener(this);
      contentPane.add(jb);

      // Add text field to content pane
      jtf = new JTextField(15);
      contentPane.add(jtf);
    }

    public void actionPerformed(ActionEvent ae) {
      jtf.setText(ae.getActionCommand());
    }
  }


Check Boxes

The JCheckBox class, which provides the functionality of a check box, is a concrete implementation of AbstractButton. Its immediate superclass is JToggleButton, which provides support for two-state buttons. Some of its constructors are shown here:

      JCheckBox(Icon i)
      JCheckBox(Icon i, boolean state)
      JCheckBox(String s)
      JCheckBox(String s, boolean state)
      JCheckBox(String s, Icon i)
      JCheckBox(String s, Icon i, boolean state)

Here, i is the icon for the button. The text is specified by s. If state is true, the check box is initially selected. Otherwise, it is not. The state of the check box can be changed via the following method:

      void setSelected(boolean state)

Here, state is true if the check box should be checked. The following example illustrates how to create an applet that displays four check boxes and a text field. When a check box is pressed, its text is displayed in the text field. The content pane for the JApplet object is obtained, and a flow layout is assigned as its layout manager. Next, four check boxes are added to the content pane, and icons are assigned for the normal, rollover, and selected states. The applet is then registered to receive item events. Finally, a text field is added to the content pane.

When a check box is selected or deselected, an item event is generated. This is handled by itemStateChanged( ). Inside itemStateChanged( ), the getItem( ) method gets the JCheckBox object that generated the event. The getText( ) method gets the text for that check box and uses it to set the text inside the text field.

  import java.awt.*;
  import java.awt.event.*;
  import javax.swing.*;
  /*
    <applet code="JCheckBoxDemo" width=400 height=50>
    </applet>
  */

  public class JCheckBoxDemo extends JApplet
  implements ItemListener {
    JTextField jtf;

    public void init() {

      // Get content pane
      Container contentPane = getContentPane();
      contentPane.setLayout(new FlowLayout());

      // Create icons
      ImageIcon normal = new ImageIcon("normal.gif");
      ImageIcon rollover = new ImageIcon("rollover.gif");
      ImageIcon selected = new ImageIcon("selected.gif");

      // Add check boxes to the content pane
      JCheckBox cb = new JCheckBox("C", normal);
      cb.setRolloverIcon(rollover);
      cb.setSelectedIcon(selected);
      cb.addItemListener(this);
      contentPane.add(cb);

      cb = new JCheckBox("C++", normal);
      cb.setRolloverIcon(rollover);
      cb.setSelectedIcon(selected);
      cb.addItemListener(this);
      contentPane.add(cb);

      cb = new JCheckBox("Java", normal);
      cb.setRolloverIcon(rollover);
      cb.setSelectedIcon(selected);
      cb.addItemListener(this);
      contentPane.add(cb);

      cb = new JCheckBox("Perl", normal);
      cb.setRolloverIcon(rollover);
      cb.setSelectedIcon(selected);
      cb.addItemListener(this);
      contentPane.add(cb);

      // Add text field to the content pane
      jtf = new JTextField(15);
      contentPane.add(jtf);
    }

    public void itemStateChanged(ItemEvent ie) {
      JCheckBox cb = (JCheckBox)ie.getItem();
      jtf.setText(cb.getText());
    }
  }


Radio Buttons

Radio buttons are supported by the JRadioButton class, which is a concrete implementation of AbstractButton. Its immediate superclass is JToggleButton, which provides support for two-state buttons. Some of its constructors are shown here:

      JRadioButton(Icon i)
      JRadioButton(Icon i, boolean state)
      JRadioButton(String s)
      JRadioButton(String s, boolean state)
      JRadioButton(String s, Icon i)
      JRadioButton(String s, Icon i, boolean state)

Here, i is the icon for the button. The text is specified by s. If state is true, the button is initially selected. Otherwise, it is not.

Radio buttons must be configured into a group. Only one of the buttons in that group can be selected at any time. For example, if a user presses a radio button that is in a group, any previously selected button in that group is automatically deselected. The ButtonGroup class is instantiated to create a button group. Its default constructor is invoked for this purpose. Elements are then added to the button group via the following method:

      void add(AbstractButton ab)

Here, ab is a reference to the button to be added to the group.

The following example illustrates how to use radio buttons. Three radio buttons and one text field are created. When a radio button is pressed, its text is displayed in the text field. First, the content pane for the JApplet object is obtained and a flow layout is assigned as its layout manager. Next, three radio buttons are added to the content pane. Then, a button group is defined and the buttons are added to it. Finally, a text field is added to the content pane.

Radio button presses generate action events that are handled by actionPerformed( ). The getActionCommand( ) method gets the text that is associated with a radio button and uses it to set the text field.

  import java.awt.*;
  import java.awt.event.*;
  import javax.swing.*;
  /*
    <applet code="JRadioButtonDemo" width=300 height=50>
    </applet>
  */

  public class JRadioButtonDemo extends JApplet
  implements ActionListener {
    JTextField tf;

    public void init() {

      // Get content pane
      Container contentPane = getContentPane();
      contentPane.setLayout(new FlowLayout());

      // Add radio buttons to content pane
      JRadioButton b1 = new JRadioButton("A");
      b1.addActionListener(this);
      contentPane.add(b1);

      JRadioButton b2 = new JRadioButton("B");
      b2.addActionListener(this);
      contentPane.add(b2);

      JRadioButton b3 = new JRadioButton("C");
      b3.addActionListener(this);
      contentPane.add(b3);

      // Define a button group
      ButtonGroup bg = new ButtonGroup();
      bg.add(b1);
      bg.add(b2);
      bg.add(b3);

      // Create a text field and add it
      // to the content pane
      tf = new JTextField(5);
      contentPane.add(tf);
    }

    public void actionPerformed(ActionEvent ae) {
      tf.setText(ae.getActionCommand());
    }
  }

A Tour of Swing-Icons & Text Fields - Java Tutorials

A Tour of Swing-Icons

In Part II, you saw how to build user interfaces with the AWT classes. Here, we will take a tour of a supercharged alternative called Swing. Swing is a set of classes that provides more powerful and flexible components than are possible with the AWT. In addition to the familiar components, such as buttons, check boxes, and labels, Swing supplies several exciting additions, including tabbed panes, scroll panes, trees, and tables. Even familiar components such as buttons have more capabilities in Swing. For example, a button may have both an image and a text string associated with it. Also, the image can be changed as the state of the button changes.

Unlike AWT components, Swing components are not implemented by platform-specific code. Instead, they are written entirely in Java and, therefore, are platform-independent. The term lightweight is used to describe such elements.

The number of classes and interfaces in the Swing packages is substantial, and this chapter provides an overview of just a few. Swing is an area that you will want to explore further on your own.

The Swing component classes that are used in this book are shown here:

Class  --  Description

AbstractButton:  Abstract superclass for Swing buttons.

ButtonGroup:  Encapsulates a mutually exclusive set of buttons.

ImageIcon:  Encapsulates an icon.

JApplet:  The Swing version of Applet.

JButton:  The Swing push button class.

JCheckBox:  The Swing check box class.

JComboBox:  Encapsulates a combo box (an combination of a drop-down list and text field).

JLabel:  The Swing version of a label.

JRadioButton:  The Swing version of a radio button.

JScrollPane:  Encapsulates a scrollable window.

JTabbedPane:  Encapsulates a tabbed window.

JTable:  Encapsulates a table-based control.

JTextField:  The Swing version of a text field.

JTree:  Encapsulates a tree-based control.


The Swing-related classes are contained in javax.swing and its subpackages, such as javax.swing.tree. Many other Swing-related classes and interfaces exist that are not examined in this chapter.

The remainder of this chapter examines various Swing components and illustrates them through sample applets.


JApplet

Fundamental to Swing is the JApplet class, which extends Applet. Applets that use Swing must be subclasses of JApplet. JApplet is rich with functionality that is not found in Applet. For example, JApplet supports various “panes,” such as the content pane, the glass pane, and the root pane. For the examples in this chapter, we will not be using most of JApplet’s enhanced features. However, one difference between Applet and JApplet is important to this discussion, because it is used by the sample applets in this chapter. When adding a component to an instance of JApplet, do not invoke the add( ) method of the applet. Instead, call add( ) for the content pane of the JApplet object. The content pane can be obtained via the method shown here:

      Container getContentPane( )

The add( ) method of Container can be used to add a component to a content pane. Its form is shown here:

      void add(comp)

Here, comp is the component to be added to the content pane.


Icons and Labels

In Swing, icons are encapsulated by the ImageIcon class, which paints an icon from an image. Two of its constructors are shown here:

      ImageIcon(String filename)
      ImageIcon(URL url)

The first form uses the image in the file named filename. The second form uses the image in the resource identified by url.

The ImageIcon class implements the Icon interface that declares the methods shown here:

Method  --  Description

int getIconHeight( ):  Returns the height of the icon in pixels.

int getIconWidth( ):  Returns the width of the icon in pixels.

void paintIcon(Component comp, Graphics g, int x, int y):  Paints the icon at position x, y on the graphics context g. Additional information about the paint operation can be provided in comp.


Swing labels are instances of the JLabel class, which extends JComponent. It can display text and/or an icon. Some of its constructors are shown here:

      JLabel(Icon i)
      Label(String s)
      JLabel(String s, Icon i, int align)

Here, s and i are the text and icon used for the label. The align argument is either LEFT, RIGHT, CENTER, LEADING, or TRAILING. These constants are defined in th SwingConstants interface, along with several others used by the Swing classes.

The icon and text associated with the label can be read and written by the following methods:

      Icon getIcon( )
      String getText( )
      void setIcon(Icon i)
      void setText(String s)

Here, i and s are the icon and text, respectively.

The following example illustrates how to create and display a label containing both an icon and a string. The applet begins by getting its content pane. Next, an ImageIcon object is created for the file france.gif. This is used as the second argument to the JLabel constructor. The first and last arguments for the JLabel constructor are the label text and the alignment. Finally, the label is added to the content pane.

  import java.awt.*;
  import javax.swing.*;
  /*
    <applet code="JLabelDemo" width=250 height=150>
    </applet>
  */

  public class JLabelDemo extends JApplet {

    public void init() {
      // Get content pane
      Container contentPane = getContentPane();

      // Create an icon
      ImageIcon ii = new ImageIcon("france.gif");

      // Create a label
      JLabel jl = new JLabel("France", ii, JLabel.CENTER);

      // Add label to the content pane
      contentPane.add(jl);
    }
  }




Text Fields

The Swing text field is encapsulated by the JTextComponent class, which extends JComponent. It provides functionality that is common to Swing text components. One of its subclasses is JTextField, which allows you to edit one line of text. Some of its constructors are shown here:

      JTextField( )
      JTextField(int cols)
      JTextField(String s, int cols)
      JTextField(String s)

Here, s is the string to be presented, and cols is the number of columns in the text field.

The following example illustrates how to create a text field. The applet begins by getting its content pane, and then a flow layout is assigned as its layout manager. Next, a JTextField object is created and is added to the content pane.

  import java.awt.*;
  import javax.swing.*;
  /*
    <applet code="JTextFieldDemo" width=300 height=50>
    </applet>
  */

  public class JTextFieldDemo extends JApplet {
    JTextField jtf;

    public void init() {

      // Get content pane
      Container contentPane = getContentPane();
      contentPane.setLayout(new FlowLayout());

      // Add text field to content pane
      jtf = new JTextField(15);
      contentPane.add(jtf);
    }
  }

The Java Beans API & Using Bean Builder - Java Tutorials

The Java Beans API

The Java Beans functionality is provided by a set of classes and interfaces in the java.beans package. This section provides a brief overview of its contents. Below lists the interfaces in java.beans and provides a brief description of their functionality.


The Interfaces Defined in java.beans

AppletInitializer:  Methods in this interface are used to initialize Beans that are also applets.

BeanInfo:  This interface allows a designer to specify information about the properties, events, and methods of a Bean.

Customizer:  This interface allows a designer to provide a graphical user interface through which a Bean may be configured.

DesignMode:  Methods in this interface determine if a Bean is executing in design mode.

ExceptionListener:  A method in this interface is invoked when an exception has occurred. (Added by Java 2, version 1.4.)

PropertyChangeListener:  A method in this interface is invoked when a bound property is changed.

PropertyEditor:  Objects that implement this interface allow designers to change and display property values.

VetoableChangeListener:  A method in this interface is invoked when a constrained property is changed.

Visibility:  Methods in this interface allow a Bean to execute in environments where a graphical user interface is not available.


The Classes Defined in java.beans

BeanDescriptor:  This class provides information about a Bean. It also allows you to associate a customizer with a Bean.

Beans:  This class is used to obtain information about a Bean.

DefaultPersistenceDelegate:  A concrete subclass of PersistenceDelegate. (Added by Java 2, version 1.4.)

Encoder:  Encodes the state of a set of Beans. Can be used to write this information to a stream. (Added by Java 2, version 1.4.)

EventHandler:  Supports dynamic event listener creation. (Added by Java 2, version 1.4.)

EventSetDescriptor:  Instances of this class describe an event that can be generated by a Bean.

Expression:  Encapsulates a call to a method that returns a result. (Added by Java 2, version 1.4.)

FeatureDescriptor:  This is the superclass of the PropertyDescriptor, EventSetDescriptor, and MethodDescriptor classes.

IndexedPropertyDescriptor:  Instances of this class describe an indexed property of a Bean.

IntrospectionException:  An exception of this type is generated if a problem occurs when analyzing a Bean.

Introspector:  This class analyzes a Bean and constructs a BeanInfo object that describes the component.

MethodDescriptor:  Instances of this class describe a method of a Bean.

ParameterDescriptor:  Instances of this class describe a method parameter.

PersistenceDelegate:  Handles the state information of an object. (Added by Java 2, version 1.4.)

PropertyChangeEvent:  This event is generated when bound or constrained properties are changed. It is sent to objects that registered an interest in these events and implement either the PropertyChangeListener or VetoableChangeListener interfaces.

PropertyChangeListenerProxy:  Extends EventListenerProxy and implements PropertyChange Listener. (Added by Java 2, version 1.4.)

PropertyChangeSupport:  Beans that support bound properties can use this class to notify PropertyChangeListener objects.

PropertyDescriptor:  Instances of this class describe a property of a Bean.

PropertyEditorManager:  This class locates a PropertyEditor object for a given type.

PropertyEditorSupport:  This class provides functionality that can be used when writing property editors.

PropertyVetoException:  An exception of this type is generated if a change to a constrained property is vetoed.

SimpleBeanInfo:  This class provides functionality that can be used when writing BeanInfo classes.

Statement:  Encapsulates a call to a method. (Added by Java 2, version 1.4.)

VetoableChangeListenerProxy:  Extends EventListenerProxy and implements VetoableChange Listener. (Added by Java 2, version 1.4.)

VetoableChangeSupport:  Beans that support constrained properties can use this class to notify VetoableChangeListener objects.

XMLDecoder:  Used to read a Bean from an XML document. (Added by Java 2, version 1.4.)

XMLEncoder:  Used to write a Bean to an XML document. (Added by Java 2, version 1.4.)


A complete discussion of these classes and interfaces is beyond the scope of this book. However, the following program illustrates the Introspector, BeanDescriptor, PropertyDescriptor, and EventSetDescriptor classes and the BeanInfo interface. It lists the properties and events of the Colors Bean that was developed earlier in this chapter.

  // Show properties and events.
  package sunw.demo.colors;
  import java.awt.*;
  import java.beans.*;
  public class IntrospectorDemo {
    public static void main(String args[]) {
      try {
        Class c = Class.forName("sunw.demo.colors.Colors");
        BeanInfo beanInfo = Introspector.getBeanInfo(c);
        BeanDescriptor beanDescriptor = 
                       beanInfo.getBeanDescriptor();

        System.out.println("Bean name = " +
                           beanDescriptor.getName());

        System.out.println("Properties:");
        PropertyDescriptor propertyDescriptor[] =
          beanInfo.getPropertyDescriptors();
        for(int i = 0; i < propertyDescriptor.length; i++) {
          System.out.println("\t" + propertyDescriptor[i].
                             getName());
        } 

        System.out.println("Events:");
        EventSetDescriptor eventSetDescriptor[] =
          beanInfo.getEventSetDescriptors();
        for(int i = 0; i < eventSetDescriptor.length; i++) {
          System.out.println("\t" + eventSetDescriptor[i].
                             getName());
        }
      }
      catch(Exception e) {
        System.out.println("Exception caught. " + e);
      }
    }
  }

The output from this program is the following:

  Bean name = Colors
  Properties:
              rectangular
  Events:
              propertyChange
              component
              mouseMotion
              mouse
              hierarchy
              key
              focus
              hierarchyBounds
              inputMethod




Using Bean Builder

As explained at the start of the chapter, the BDK is not compatible with Java 2, version 1.4. Instead, 1.4 users will need to use the new Bean Builder tool for Bean development. At the time of this writing, Bean Builder is available only as a beta release, and its final form and feature set are subject to change. However, because it is the tool that Java 2, version 1.4 users must use to develop Beans, an overview of Bean Builder is presented here. (Subsequent editions of this book will cover Bean Builder in detail after it is a released product.) Keep in mind that the basic Bean information, such as introspection, described earlier, also applies to Beans used by Bean Builder. Bean Builder is available from http://java.sun.com.

Bean Builder is similar to the BeanBox offered by the BDK, except that it is more powerful and sophisticated. Its operation is also similar to the BeanBox except that it is easier to use. Perhaps the most striking feature of Bean Builder is that it supports two separate modes of operation: design and test. In design mode, you construct a Bean-based application, adding the various components, and wiring them together. In test mode, also called run-time mode, the application is executed and all of the components are live. Thus, it is extremely easy to construct and then test your application. Futhermore, you switch between these two modes by checking or clearing a single check box.

The top (main) window holds the current palette set. This includes a default palette from which you can choose various user-interface objects, such as buttons, scroll bars, lists, and menus. These are Swing rather than AWT objects. But no knowledge of Swing is required to follow along with the example developed later in this section.) You can also load other palettes and JAR files. Each component has associated with it a set of properties. You can examine and set these using the Property Inspector window provided by Bean Builder. The third window, called the design window (or, designer for short), is the window in which you will assemble various components into an application.

In general, to build an application, you will select items from a palette and instantiate them on the designer, setting their properties as necessary by using the Property Inspector window. Once you have assembled the components, you will wire them together by dragging a line from one to another. In the process, you will define the input and output methods that will be called, and what action causes them to be called. For example, you might wire a push button to a text field, specifying that when the push button is pressed, the text field will be cleared.


Building a Simple Bean Builder Application

It is really quite easy to build an application using Bean Builder. In this section, we will walk through the construction of a very simple one that contains a label, a slider control, and a scroll bar. When the slider control is moved, the scroll bar is also moved by the same amount, and vice versa. Thus, moving one causes the other to move, too. Once you have completed this walk through, you will be able to easily build other applications on your own.

First, create a new project by selecting New from the File menu. Next, select javax.swing.JFrame in the list at the top of the Property Inspector window. JFrame is the top-level Swing class for the design window. Next, scroll down in the Property Inspector window until you find title. Change the title to “A Bean Builder App”.

Next, we will add a label to the design. Click on the label button in the Swing palette. This instantiates a JLabel object, which is the Swing class for a label. Then, move the mouse to the designer and outline a rectangle near the top of the window. This defines were the text will go. Then, using the Property Inspector window, find the text entry. Change it to “Move slider or scroll bar.”  fter you do this. Now, find the horizontalAlignment field in the Property Inspector and change its value to CENTER. This will center the text within the label.

Next, select a slider from the palette and add it to the designer. Then, add a scroll bar. The slider is an instance of the Swing class JSlider and the scroll bar is an instance of the Swing class JScrollbar. By default, both the slider and the scroll bar have the same range (0 to 100), so the value of one will translate directly to the value of the other. To make your application look like the one in this book.

Now it is time to wire the components together. To do this, you will position the mouse pointer over one of the connection handles, then drag a “wire” from the connection handle on one component to a connection handle on another component. The component at which you start is the source of some event and the component at which you end is the recipient of the event. Each component has four connection handles, and it doesn’t matter which one you choose. Begin by wiring a connection from the slider to the scroll bar.

After you have completed the connection, the Interaction Wizard will appear. It lets you specify how the two components communicate. In this case, you will define what takes place when the slider is moved. On the first page you will select the event method that will be called when the source object (in this case, the slider) changes position. First, select the Event Adapter radio button (if it is not already selected). Then, select change in the Event Sets list. In Event Methods, stateChanged(ChangeEvent) should already be selected. 

Press Next. You will now select the method on the target object (in this case, the scroll bar) that you want called when the source object changes. In this case, select the JScrollbar method setValue(int). It sets the current position of the scroll bar.

Press Next. Now, select the “getter” method that will supply the argument to setValue( ). In this case, it will be JSlider’s getValue( ) method, which returns the current position of the slider. A “getter” is a method that uses the get design pattern. Now, press finish. This completes the connection. Now, each time the slider changes, the setValue( ) method of the scroll bar is called with an argument supplied by the getValue( ) method of the slider. Thus, moving the slider also causes the scroll bar to move.

Next, repeat this process, except this time, wire the connection from the scroll bar to the slider box. Finally, test the application. To do this, uncheck the Design Mode check box. This causes the application to execute. Try moving the slider box. When it moves, the scroll bar automatically moves, too. This is because of the connection that we wired from the slider to the scroll bar. Assuming that you also wired the reverse connection, moving the scroll bar will cause the slider to move.

You can save your application by selecting Save in the file menu. The Bean Builder is a powerful, yet easy to use development tool. If Bean development is in your future, you will want to master its features. The best way to do this is to create a number of sample Bean applications. Also, try creating your own Beans and loading them into the palette. (To do so, create a JAR file containing your Beans, as described earlier.)