Showing posts with label Java GUI. Show all posts
Showing posts with label Java GUI. Show all posts

Monday, February 13, 2012

Painting Swing components

Painting GUI components

In Java, components are rendered on screen in a process known as painting. Although this is usually handled automatically, there are occasions when you need to trigger repainting, or modify the default painting for a component.



The core painting mechanism is based on the Abstract Windowing Toolkit (AWT). In newer versions of Java, Swing painting mechanisms are based on and extend the functionality of AWT mechanisms.
Components can be heavyweight or lightweight. A heavyweight component has its own native screen peer. For a lightweight component to exist there must be a heavyweight further up the containment hierarchy. So lightweight components are more efficient. Swing components tend to be lightweight.

Painting for lightweight and heavyweight components differs slightly.
Painting is triggered when a GUI element is launched or altered in any way. This can be caused by
  • a system event
  • an application event
a system event
System-triggered painting operations are caused when a system requests a component to be rendered onscreen for the first time, resized, or repaired.

If you open the Save As window in an application, then a system request is triggered.
an application event
Application-triggered painting events occur when the internal state of an application changes and requires components to be updated.

For example, if an item is selected, the application might send a request for the item to be highlighted.
Painting in AWT
When a paint request is triggered, AWT uses a callback mechanism to paint the lightweight and heavyweight components of a GUI.

You should place the code for rendering the component in the relevant overriding paint method of the java.awt.Component class. The method is invoked whenever a system or application request is triggered.
public void paint(Graphics g)
The paint method is not invoked directly. Instead, you call the repaint method to schedule a call to paint correctly.

The Graphics object parameter is pre-configured with the state required to draw and render a component. The Graphic parameter can be reconfigured to customize painting.

public void repaint()
public void repaint(long tm)
public void repaint(int x, int y, int width, int height)
public void repaint(long tm, int x, int y,
  int width, int height)

For complex components, you should specify the region to be rendered using the arguments of the repaint method. The updated region is referred to as the clip rectangle.

The whole component is repainted if no arguments are given.

public void repaint()
public void repaint(long tm)
public void repaint(int x, int y, int width, int height)
public void repaint(long tm, int x, int y,
  int width, int height)

You can use an overridden update method to handle application-triggered painting differently from system-triggered painting.

For application-triggered paint operations, AWT calls the update method. If the component doesn't override the update() method, the default update method paints heavyweight components by clearing the background and calling the paint method.

The process of updating specified areas of a component is known as incremental painting. Incremental painting is not supported by lightweight components.
Consider the code that is used to refresh the applet when a user types text. You first create the ke instance to represent the event of typing a key.

public void keyTyped(keyEvent ke) {
  msg += ke.getKeyChar();
  repaint();
}

You call the ke instance's getKeyChar method to determine the value of the typed key. You assign the value to a variable - msg in this case - using the += overloaded operator.

You then call the repaint method, which in turn calls the overridden paint method. The value of the key typed - msg - is passed to the paint method and the key character is painted onscreen.


Painting in Swing
Painting Swing components is based on the AWT callback method, so it supports the paint and repaint methods. Swing painting also extends the functionality of paint operations with a number of additional features.

The Swing API, RepaintManager, can be used to customize the painting of Swing components. In addition, Swing painting supports Swing structures, such as borders and double-buffering.

Double-buffering is supported by default. Removing double-buffering is not recommended.
Because lightweight components are contained within heavyweight components, the painting of lightweight components is triggered by the paint method of the heavyweight component.
When the paint method is called, it is translated to all lightweight components using the java.awt.Container class's paint method. This causes all defined areas to be repainted.
There are three customized callbacks for Swing components, which factor out a single paint method into three subparts. These are
  • paintComponent()
  • paintBorder()
  • paintChildren()
paintComponent()
You use the paintComponent method to call the UI delegate object's paint method. The paintComponent method passes a copy of the Graphics object to the UI delegate object's paint method. This protects the rest of the paint code from irrevocable changes.

You cannot call the paintComponent method if UI delegate is set to null.
paintBorder()
You use the paintBorder method to paint a component's border.
paintChildren()
You use the paintChildren method to paint a component's child components.
You need to bear several factors in mind when designing a Swing paint operation.

Firstly, application-triggered and system-triggered requests call the paint or repaint method of a Swing component, but never the update method. Also, the paint method is never called directly. You can trigger a future call to it by invoking the repaint method.

As with AWT components, it is good practice to define the clip rectangle using the arguments of the repaint method. Using the clip rectangle to narrow down the area to be painted makes the code more efficient.

You can customize the painting of Swing components using two properties, namely
  • opaque
  • optimizedDrawingEnabled
opaque
You use the opaque property to clear the background of a component and repaint everything contained within the paintComponent method. To do this, opaque must be set to true, which is the default. Setting opaque to true reduces the amount of screen clutter caused by repainting a component's elements.
optimizedDrawingEnabled
The optimizedDrawingEnabled property controls whether components can overlap. The default value of the optimizedDrawingEnabled property is true.
Setting either the opaque or the optimizedDrawingEnabled property to false is not advised unless absolutely necessary, as it causes a large amount of processing.

You use the paintComponent method for Swing component extensions that implement their own paint code. The scope of these component extensions need to be set in the paintComponent method.

The paintComponent method is structured in the same way as the paint method.

// Custom JPanel with overridden paintComponent method
class MyPanel extends JPanel {
 
public MyPanel(LayoutManager layout) {
  super (layout) ;
}
 
public void paintComponent(Graphics g) {
  // Start by clearing the current screen
  g.clearRect( getX(), getY(), getWidth(), getHeight()) ;
  g.setColor (Color.red) ;
  int[] x = {30, 127, 56, 355, 240, 315 } ;
  int[] y = {253, 15, 35, 347, 290, 265} ;
  //Draw complex shape on-screen and fill it
  g.drawPolygon (x, y, 5) ;
  g.fillPolygon (x, y, 5) ;
  }
}

Summary

Painting is the process of rendering components onscreen. Heavyweight components have matching native peers, whereas lightweight components rely on a heavyweight container to do their painting. Painting is triggered by requests. System-triggered requests occur when windows are launched, resized, or repaired. Application-triggered requests occur when the internal state of an application changes.

AWT uses a callback method to invoke an overridden version of the paint method of the java.awt.Component class. You define the area that requires painting, the clip rectangle, using the arguments of the repaint method. You can also override the update method for application-triggered paint operations.

Swing painting is based on AWT painting and then adds further functionality. Heavyweight containers translate the paint method to all the lightweight components contained within them. Swing painting has three customized callbacks and two properties that you use to customize the Swing painting operation.

Coding an event handler

Listeners represent each event they handle with a separate method. And each listener method takes an event parameter of the appropriate type.



For example, the actionPerformed method of the ActionListener interface takes an ActionEvent object as a parameter.
public void actionPerformed (ActionEvent e)
In the code example, the class implements the MouseListener's mouseClicked method, which takes a MouseEvent object as a parameter.
public void mouseClicked (MouseEvent e) {
  String search = frame.t.getText( );
  String searchField = frame.scribble.getText( );
  if ( (search != null) & (search != " ") ) {
    int i = searchField.indexOf (search);
    if (i == -1)
      frame.display.setText("Search string not found");
    else {
      frame.display.setText("Search string found");
      // Highlight the found search string
      frame.scribble.select(i, i + search.length( ) );
    }
  }
}
When you implement a listener interface, you must provide empty implementations for any of its methods that you do not want to use.

Consider the code that provides empty implementations for the four MouseListener methods it doesn't use.
public void mouseClicked (MouseEvent e) {
  String search = frame.t.getText( );
  String searchField = frame.scribble.getText( );
  if ( (search != null) & (search != " ") ) {
    int i = searchField.indexOf (search);
    if (i == -1)
      frame.display.setText("Search string not found");
    else {
      frame.display.setText("Search string found");
      // Highlight the found search string
      frame.scribble.select(i, i + search.length( ) );
    }
  }
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
Java provides an adapter for each interface that has more than one method. For example, the WindowListener interface has a corresponding adapter class that implements it. This is called WindowAdapter.

To handle and perform this kind of event, a WindowEvent must be passed to a WindowListener or WindowAdapter object that is registered to a Window component.

The sample code shows how this is performed:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class SampleS {
    public static void main(String args[]) {
        JFrame f=new JFrame("Sample JFrame");
        f.setVisible(true);
        f.addWindowListener(new WindowAdapter() {
            public void  windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}
The addWindowListener method is used to register a WindowEvent for a Window component such as a JFrame. A windowClosing method is implemented whenever a WindowEvent occurs. This in turn closes the current window as executed by the System.exit(0) statement.
Using the adapter instead of the listener interface to handle an event often prevents you having to implement irrelevant methods that are part of the listener interface.

However, the downside is that by extending adapter classes, you prevent the event handler from extending any other class.

Supplement

Selecting the link title opens the resource in a new browser window.
View a table of listener interfaces and their adapters.
Event adapters and event listeners are commonly implemented using Java's anonymous inner classes. This allows you to register and define the event handling code all in one place and with the minimum of extraneous code.
checkBox.  {
  public void actionPerformed(ActionEvent e) {
    if (checkBox.isSelected())
      label.setText("You will be receiving special deals");
    else
      label.setText("You have chosen not to receive special deals");
  }
}
You can, for example, create an anonymous inner class that implements the ActionListener interface. To do this, you use a listener registration method - in this case, addActionListener - to register the adapter.
checkBox.MISSING CODE {
  public void actionPerformed(ActionEvent e) {
    if (checkBox.isSelected())
      label.setText("You will be receiving special deals");
    else
      label.setText("You have chosen not to receive special deals");
  }
}
component.addXXXListener (new XXXListener() {
  public void eventhandler (eventtype e) {
    // implementation   }
}
checkBox.addActionListener (new ActionListener() {
  public void actionPerformed(ActionEvent e) {
    if (checkBox.isSelected())
      label.setText("You will be receiving special deals");
    else
      label.setText("You have chosen not to receive special deals");
  }
}
You type addActionListener (new ActionListener() to register the adapter.
You have registered the ActionListener anonymous class.

Next, you define the relevant method - in this case, actionPerformed.
checkBox.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent e) {
    if (checkBox.isSelected())
      label.setText("You will be receiving special deals");
    else
      label.setText("You have chosen not to receive special deals");
  }
}
Suppose you have a List control and you add a listener to listen for ItemEvents. The listener implements the ItemListener interface, which contains one method only - the itemStateChanged method.
public void itemStateChanged (ItemEvent e)
The itemStateChanged method is invoked when the event occurs, such as when a list item is selected. The details of the event are passed to the event handler - in other words the method - via the ItemEvent argument, AccountList.
public void itemStateChanged(ItemEvent AccountList) {
  try {
    List target = (List) AccountList.getItem() ;
    int i = 0;
    while (i<6 && !(accountOptions[i].equals(target.getText()))) {
          i++;
    }
    if (e.getStateChange() == ItemEvent.DESELECTED) {
      descriptions[i] = description.getText();
    }
    if (e.getStateChange() == ItemEvent.SELECTED) {
      description.setText(details[i]);
    }
  }
}
The target object implements the ItemListener interface and is passed to ItemEvent when the event occurs. The listener is spared the details of processing individual mouse movements and mouse clicks, and instead processes semantic events, such as ItemEvent.DESELECTED or ItemEvent.SELECTED.
public void itemStateChanged(ItemEvent AccountList) {
  try {
    List target = (List) AccountList.getItem() ;
    int i = 0;
    while (i<6 && !(accountOptions[i].equals(target.getText()))) {
          i++;
    }
    if (e.getStateChange() == ItemEvent.DESELECTED) {
      descriptions[i] = description.getText()
    }
    if (e.getStateChange() == ItemEvent.SELECTED) {
      description.setText(details[i]);
    }
  }
}
The getItem method of the AccountList object is cast to a List datatype, which is assigned to target, an object of the List class.
public Object getItem()
The getItem method returns the element of the selectable control - a List in this example - affected by the selection event.
public void itemStateChanged(ItemEvent AccountList) {
  try {
    List target = (List) AccountList.getItem() ;
    int i = 0;
    while (i<6 && !(accountOptions[i].equals(target.getText()))) {
          i++;
    }
    if (e.getStateChange() == ItemEvent.DESELECTED) {
      descriptions[i] = description.getText();
    }
    if (e.getStateChange() == ItemEvent.SELECTED) {
      description.setText(details[i]);
    }
  }
}
You can use the getPoint method in the MouseEvent object to determine an event's x and y coordinates. The returned coordinates are relative to the component's x and y coordinates. You can call getPoint() at any time.

Alternatively, you can call the getX and getY methods separately.
public synchronized Point getPoint()

public int getX()

public int getY()

Implementing an event listener

To code an event handler you need to

  • declare an event handler class
  • register an instance of the class as a listener on an event source
  • include code to implement the methods
You declare an event handler class by implementing a listener interface or by extending a class that does.
Because Java allows multiple interface implementations, it's possible for a single class to implement more than one listener interface. This feature allows you to use the same class to handle different types of events.
In the example, the SearchButton class implements the MouseListener interface, so that it is capable of handling mouse events, such as mousePressed or mouseClicked.
class SearchButton extends Button implements MouseListener {
  Gui3 frame; // Refers to the parent window
  SearchButton(String caption, Gui3 frame) {
    super (caption);
    this.frame = frame;
    addMouseListener(this);
  }
}
Once you have declared the event handler class, you need to register the listener. When listeners are registered on an event source, the Java runtime system automatically invokes the correct method in the listener in response to events, using a method call from the event source.
component.addeventlListener(theListener);
Each component has a set of methods available for registering listeners - one for each event type.

In the code example, the SearchButton class registers itself to listen for mouse events using the addMouseListener method.
class SearchButton extends Button implements MouseListener {
  Gui3 frame; // Refers to the parent window
  SearchButton(String caption, Gui3 frame) {
    super (caption);
    this.frame = frame;
    addMouseListener(this);
  }
}

The AWTEvent class

All events are instances of event classes in the event class hierarchy. All classes in this hierarchy inherit from the java.util.EventObject class, and all classes in the AWT event hierarchy inherit from java.awt.AWTEvent.

The subclasses of AWTEvent can be divided into two groups:
  • low-level events
  • high-level (or semantic) events
low-level events
Low-level events are very specific user actions, such as clicking a button or moving a mouse.
high-level (or semantic) events
High-level, or semantic, events are more generalized or abstract events. They occur when a user chooses, selects, or alters something. High-level events are also known as semantic events because they abstract meaningful actions from sets of lower-level actions.
The ComponentEvent class contains five subclasses representing low-level events. These are
  • InputEvent
  • WindowEvent
  • FocusEvent
  • ContainerEvent
  • PaintEvent
InputEvent
InputEvent is the root event class for all component-level input events. This class has two subclasses - MouseEvent and KeyEvent.

The three types of key events are key pressed, key released, and key typed. Each of these key events has a corresponding method and constant. You can use the getKeyChar method to return the char representing the key that has generated the event. Mouse events occur when a mouse button is pressed or released, or when a mouse is moved. The MouseEvent class also contains the MouseWheelEvent class for mouse wheel rotation.
WindowEvent
Window events occur whenever a window

  • is activated or deactivated
  • is opened, closed, or closing
  • is reduced to an icon or restored to a fully open state
  • gains or loses focus
FocusEvent
The two focus events are focus gained and focus lost. A component gains permanent focus when it makes a successful requestFocus method call or when users click or tab to access it. And it gains temporary focus as a side-effect of another operation, such as a window deactivation or scrollbar drag.

You distinguish between permanent and temporary focus using the isTemporary method of the FocusEvent:

public boolean isTemporary()

The isTemporary method returns true if the focus was temporarily lost.
ContainerEvent
Container events occur when components are added to, or removed from, a container.
The registered container listener receives notification of an event and can obtain the identity of the new component using a getChild method call. This allows containers to easily add input event listeners to, or remove them from, their components as each component is added or removed.
PaintEvent
Paint events are generated by the AWT, not delivered to any listeners. So they are of no practical use to programmers.
The four pre-defined subclasses representing semantic events are
  • ItemEvent
  • AdjustmentEvent
  • TextEvent
  • ActionEvent
ItemEvent
Item events occur in components that have implemented the ItemSelectable interface. They represent the selection or deselection events on selectable items, such as lists, checkboxes, and pop-up menus.

Item events are generated by ItemSelectable objects, for example Checkbox, List, JComboBox, and CheckboxMenuItem. Rather than having to deal with individual mouse or click events, this high-level event is more meaningful and a listener can more easily deal with relevant events.
AdjustmentEvent
Adjustment events occur in components such as scrollbars, which have numeric values that can be incremented or decremented by the user.

For example, as a scrollbar is moved, its new position is signaled to an adjustment listener as an adjustment event.
TextEvent
Text events occur when text is entered, deleted, or edited in text entry fields.
ActionEvent
Action events include such actions as clicking a button or pressing a function key. Several different user actions may result in the same action event being generated, which means that logically-related, higher-level events can be grouped together for handling in one place.

You can use the ActionEvent class's getActionCommand method to distinguish between different types of the same semantic event.
All event types are represented as predefined constants in the different event classes to which they belong. For example, the MouseEvent has constants for MOUSE_CLICKED and MOUSE_RELEASED, whereas for KeyEvent there are such constants as KEY_PRESSED.

You can use the AWTEvent class getID method to return one of these constants and so identify the type of event that has occurred.

Event delegation

It is important to consider how users interact with the user interface when designing a graphical user interface (GUI). The GUI may require users to click, resize, or drag and drop components of the interface, and input data using the keyboard. These actions will result to an event and you need to write a code to handle them.
Event handling code deals with events generated by GUI user interaction. The best practices for coding event handlers are outlined in the event delegation model.
The event delegation model comprises three elements:
  • Event source
  • Event listener
  • Adapter
Event source
An event source is a component, such as a GUI component, that generates an event. The event source can be generated by any type of user interaction. You can also combine a number of different types of events into one event object.

For example, if a user clicks and drags an icon, you can sum up the mouse-clicked event and the mouse-moved event into one event object.

In the event delegation model, a class represents each event type. Event objects are all defined in the java.util.EventObject subclasses.

A generated event object

  • provides the methods to add or remove the source event
  • manages the list of registered event listeners
  • provides the appropriate class type to the registered event listeners
Event listener
Event listeners are objects that receive notification of an event. Components define the events they fire by registering objects called listeners for those event types. When an event is fired, an event object is passed as an argument to the relevant listener object method. The listener object then handles the event.

To receive notification of an event, the object must be registered with the event source. To subscribe to the event source, you implement the appropriate listener interface.

All listeners are implementations of the EventListener interface or one of its subinterfaces. The Java API provides a predefined listener interface for each set of event types that a source can fire. For example, the MouseListener interface deals with mouse events, and the ActionListener interface deals with action events fired by buttons and other components.

Each listener interface provides at least one method for delivering the event object to the listener, in addition to any methods required for the action. All methods take one parameter and are part of the EventObject class.
Adapter
Adapters are abstract classes that implement listener interfaces using predefined methods. These are provided for convenience.

You can use an adapter to apply one listener's methods without having to implement all other methods. Adapters provide empty implementations for all interfaces' methods, so you only need to override the method you are interested in.
SwingWorker class is designed to be used for situations where you need to have a long running task run in a background thread and provide updates to the GUI either when done or while still in progress. Subclasses of SwingWorker must implement the doInBackground method to perform the background computation.
When using the SwingWorker class, you need to subclass SwingWorker and override the doInBackground method and done method. You can code a lengthy operation inside doInBackground and add another task into the done method before updating the Swing component from the event thread.
With the release of Java SE 6.0, additional features for sorting and filtering the JTable have been added. By filtering the contents of a JTable, only the rows that match the user specified constraints are displayed. Users can click on a specific column to be able to sort the contents accordingly.
Sorting is done by associating a JTable with a RowSorter class. RowSorter maintains two mappings. One maps rows in a JTable to the elements of the underlying model and the other let you go back again. Having two mappings allows you to do sorting and filtering. The class is generic enough to work with both TableModel and ListModel. TableRowSorter class is used to work with a JTable.
In the simplest case, you pass the TableModel to the TableRowSorter constructor and then pass the created RowSorter into the setRowSorter method of JTable.

The code shows an example:
           TableModel model = new DefaultTableModel(rows, columns) {
               public Class getColumnClass(int column) {
                   Class returnValue;
                   if ((column >= 0) && (column < getColumnCount())) {
                     returnValue = getValueAt(0, column).getClass();
                   } else {
                       returnValue = Object.class;
                   }
                   return returnValue;
             }
           };

           JTable table = new JTable(model);
           RowSorter<TableModel> sorter =new TableRowSorter<TableModel>(model);
           table.setRowSorter(sorter);
           JScrollPane pane = new JScrollPane(table);
           frame.add(pane, BorderLayout.CENTER);
           frame.setBounds(400, 350, 300, 225);
     frame.setResizable(false);   
           frame.setVisible(true);
       
     }
}
To perform filtering on a JTable, a RowFilter needs to be associated with the TableRowSorter and use it to filter the contents of a table using the include method.

The syntax for the include method is:
boolean include(RowFilter.Entry<? extends M,? extends I> entry)
For each entry in the model associated with the RowSorter, the method indicates whether the specified entry should be shown in the current view of the model. In many cases, you don't need to create your own RowFilter implementation.
In the given example, we use the regexFilter() method which uses a regular expression for filtering.
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.regex.*;

   public class SampleFilterJTable {
     public static void main(String args[]) {
           JFrame frame = new JFrame("Sorting JTable");
           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           Object rows[][] = {
             {"CLSRE", "Callinsure", 388.44},
                    {"INTRSW", "Inter-Swift", 12.56},
                    {"BRCD", "Brocadero", 57.13},
                    {"MIMPS", "Med-Imps", 32.52},
                    {"CBCO", "Custom Boat Co.", 443.26},
                    {"SETLS",  "Sharp-End Tools", 12.90},
                     {"PHLX", "Phlogistix", 31.25},
               {"MTLD", "Mathemetric Ltd.", 45.89}
           };
           Object columns[] = {"Symbol", "Name", "Price"};
           TableModel model =
              new DefaultTableModel(rows, columns) {
             public Class getColumnClass(int column) {
               Class returnValue;
               if ((column >= 0) && (column < getColumnCount())) {

Sunday, February 12, 2012

Setting size hints

To ensure that components are positioned well, you may require certain components to adhere to maximum or minimum specifications.

You can use size hints to specify a number of preferred maximum and minimum component sizes.
The layout manager implements the specified sizes for container components. However, only BoxLayout and SpringLayout implement the requested maximum size for components.
To set size hints, you use the component's setMinimumSize, setPreferredSize, and setMaximumSize methods.

For example, you can use the setMaximumSize method to set the size hint for the component to 150 by 300 pixels.

Alternatively, you can override the appropriate getter methods of a component using a subclass. The component getter methods are getMinimumSize, getPreferredSize, and getMaximumSize.
component.setMaximumSize(new Dimension(150, 300));

You can also provide alignment hints for components, although these are only implemented by the BoxLayout layout manager.
You set alignment hints using the component's setAlignmentX and setAlignmentY methods. For example, you can specify that a button is aligned 40 pixels from the top.

As with size hints, you can also override the component's getAlignmentX and getAlignmentY methods by creating a subclass.

myButton.setAlignmentX( (float) 40 ) ;

Using absolute positioning

All Java components have a platform-dependent, preferred size. This specifies how large the component should be, notwithstanding the layout policy of the layout manager used by its container. A component's preferred size is usually the size that is big enough for a user to see its function on a GUI.
You can use absolute positioning in conjunction with a layout manager to position components. When using absolute positioning, you are required to specify the size and position of each component within the container. You can modify a component's position and size by using the Component class's setBounds method.

public void setBounds(int x, int y, int width, int height);

When a layout manager lays out components, it takes into account its own layout policy and the preferred sizes of its container's components.

If there is a clash between the layout policy of the layout manager and the preferred size of a component that it is positioning, the layout policy takes precedence.

For example, if a button's preferred size is larger than the size and position required by the layout manager's layout policy, the button will be resized by the layout manager.

The Component class has instance variables that specify the size and position of components.
The variables x and y specify the component's position in pixels, relative to the top left-hand corner of its container.

The width and height variables are also measured in pixels.
To use absolute positioning, you need to set the container's layout property to null.

public class LayoutApplet extends Applet {
import java.awt.*;
import java.applet.Applet;

public class NewButton extends Applet {
  public void init (){
    MISSING CODE
  }
}
public class LayoutApplet extends Applet {
import java.awt.*;
import java.applet.Applet;

public class NewButton extends Applet {
  public void init (){
    setLayout (null);
  }
}

You type setLayout (null); to set the layout property to null.
To set the container's layout property to null, you call the setLayout method and give it a parameter of null.

import java.awt.*;
import java.applet.Applet;

public class NewButton extends Applet {
  public void init (){
    setLayout (null);
  }
}

Note

Using absolute positioning for all components on your interface is not advised because components aren't implemented consistently across platforms. Components also don't resize well when you resize the top-level container. You should use absolute positioning only when it is really necessary.
Consider the code in which you add a button to the applet NewButton. Its position is four pixels in and six pixels down from the top left-hand corner of the container. You also specify the size of the button – 200 pixels wide and 400 pixels high.
import java.awt.*;
import java.applet.Applet;

public class NewButton extends Applet {
  public void init (){
    setLayout (null) ;
    Button b = new Button ("Exit");
    b.setBounds(4,6,200,400);
    add(b);
  }
}
When you run the NewButton applet, the button appears the exact size defined in the setBounds method. This is because the applet is not using the layout manager class.

This may cause only part of the button to be shown or the button may not be visible at all. You may need to resize the JFrame window to see the button.

import java.awt.*;
import java.applet.Applet;

public class NewButton extends Applet {
  public void init (){
    setLayout (null) ;
    Button b = new Button ("Exit");
    b.setBounds(4,6,200,400);
    add(b);
  }
}

Using layout managers

The type of layout manager that you use depends largely on your display requirements.
There are five original layout managers commonly used. These are
  • FlowLayout
  • GridLayout
  • GridBagLayout
  • BorderLayout
  • CardLayout
FlowLayout
The FlowLayout class provides the simplest means of laying out components. It is the default layout for certain Containers. The Panel employs the FlowLayout as its default manager.

FlowLayout inserts components in a row – from left to right – as you add them to the container. When a component won't fit at the end of a row, it's wrapped to the start of a new row.

An example of the code for FlowLayout is

import java.awt.*;
import java.applet.Applet;

public class DemoFlowLayout extends Applet {
  public void init () {
    setLayout (new FlowLayout ());
    Button b1 = new Button("one");
    Button b2 = new Button("two");
    Button b3 = new Button("three");
    Button b4 = new Button("four");
    Button b5 = new Button("five");
    add(b1);
    add(b2);
    add(b3);
    add(b4);
    add(b5);
  }
}


The default alignment of the FlowLayout class is centered. However, you can change this to left or right alignment by passing the constants FlowLayout.LEFT or FlowLayout.RIGHT to the FlowLayout constructor. For example, the code for left alignment is

setLayout(new FlowLayout(FlowLayout.LEFT));

An example of a flow layout that is aligned to the left is

import java.awt.*;
import java.applet.Applet;

public class DemoFlowLayout extends Applet {
  public void init () {
    setLayout(new FlowLayout(FlowLayout.LEFT));
    Button b1 = new Button("one");
    Button b2 = new Button("two");
    Button b3 = new Button("three");
    Button b4 = new Button("four");
    Button b5 = new Button("five");
    add(b1);
    add(b2);
    add(b3);
    add(b4);
    add(b5);
  }
}


FlowLayout creates a default gap of 5 pixels between components. However, you can change both the horizontal and vertical gap between components by passing appropriate arguments to the FlowLayout constructor.

For instance, the code example specifies a horizontal gap of 10 pixels and a vertical gap of 4 pixels.

setLayout (new FlowLayout (FlowLayout.CENTER,10,4));

Another complete example of the code for FlowLayout follows.

import java.awt.*;
import java.applet.Applet;

public class NewApplet extends Applet {
  public void init () {
    setLayout (new FlowLayout (FlowLayout.CENTER,10,4));
    Label 11 = new Label ("First Name: ");
    TextField t1 = new TextField (12);
    Label 12 = new Label ("Last Name: ");
    TextField t2 = new TextField (12);
    add(l1);
    add(t1);
    add(l2);
    add(t2);
  }
}


FlowLayout is best suited to simple layouts where components need to be displayed at their natural size. For a large number of components, you should use another layout manager.
GridLayout
You can use the GridLayout class to make a number of components of the same size. The GridLayout layout manager divides a panel into a grid of uniform cells. It then adds components one at time, building up cell rows and columns from left to right, top to bottom.

The code to implement this GridLayout is

import java.awt.*;
import java.applet.Applet;

public class DemoGridLayout extends Applet {
  public void init () {
    Panel p1 = new Panel ();
    //set layout for panel p1
    p1.setLayout (new GridLayout(2,3));
    Button b1 = new Button("one");
    Button b2 = new Button("two");
    Button b3 = new Button("three");
    Button b4 = new Button("four");
    Button b5 = new Button("five");
    p1.add(b1);
    p1.add(b2);
    p1.add(b3);
    p1.add(b4);
    p1.add(b5);
  }
}


You set the number of rows and columns for a particular panel in the constructor of its GridLayout object. Consider the code that sets the GridLayout with two rows and three columns.

p1.setLayout (new GridLayout(2,3));
Suppose you decide to add the buttons in sequence. The first three buttons fill the first row of a two-row by three-column grid. Then the fourth and fifth buttons are added in the second row.

Here is the code again.

import java.awt.*;
import java.applet.Applet;

public class DemoGridLayout extends Applet {
  public void init () {
    Panel p1 = new Panel ();
    //set layout for panel p1
    p1.setLayout (new GridLayout(2,3));
    Button b1 = new Button("one");
    Button b2 = new Button("two");
    Button b3 = new Button("three");
    Button b4 = new Button("four");
    Button b5 = new Button("five");
    p1.add(b1);
    p1.add(b2);
    p1.add(b3);
    p1.add(b4);
    p1.add(b5);
  }
}


The Gridlayout class has a default gap between components of 0 pixels, but you can specify horizontal and vertical gaps by passing suitable arguments.

Consider the code that creates a grid that can hold up to 12 components in three rows and four columns, with a horizontal gap of 10 pixels and a vertical gap of 14 pixels between components.

p1.setLayout (new GridLayout(3,4,10,14));

The code to implement the described GridLayout is

import java.awt.*;
import java.applet.Applet;

public class DemoGridLayout2 extends Applet {
  public void init () {
    Panel p1 = new Panel ();
    //set layout for panel p1
    p1.setLayout (new GridLayout(3,4,10,14));
    Button b1 = new Button("one");
    Button b2 = new Button("two");
    Button b3 = new Button("three");
    Button b4 = new Button("four");
    Button b5 = new Button("five");
    p1.add(b1);
    p1.add(b2);
    p1.add(b3);
    p1.add(b4);
    p1.add(b5);
  }
}


GridLayout is used to display components added in a tabular manner. Such components will have the same row and column size no matter the size of the container. It is also used for displaying a single component in as much space as possible.

Although GridLayout is useful when you need to lay out a number of components of similar size, you may not have sufficient control over the end result for variable component sizes.
GridBagLayout
The GridBagLayout class is similar to GridLayout in that it uses a grid of rows and columns. However, these rows and columns do not need to be of uniform width and height.

GridBagLayout places the components into the grid's cells but allows the cells to adjust to the required size of the components.

Each component has a GridBagConstraints object that specifies how it should be displayed.

An example of a GridLayout method is

table.setLayout (new GridLayout (5,9));

The flexibility of GridBagLayout lends itself to the layout of many components. Although GridBagLayout is highly functional, it can be very complex to program. You should carefully weigh the benefits of GridBagLayout against the benefits of other more easily programmed layout managers.

For instance, suppose your display incorporates a complicated layout of components and you do not want to use the GridBagLayout class. In this case, you can consider grouping the components into one or more panels and using appropriate layout managers with each panel.
BorderLayout
The BorderLayout manager can arrange components into five separate areas of a container – represented by the BorderLayout constants NORTH, SOUTH, EAST, WEST, and CENTER.

An example of BorderLayout is

import java.awt.*;
import java.applet.Applet;

public class DemoBorderLayout extends Applet {
  public void init () {
    Panel p1 = new Panel();
    //set layout for panel p1
    p1.setLayout (new BorderLayout());
    Button b1 = new Button("Top");
    Button b2 = new Button("Bottom");
    Button b3 = new Button("Right");
    Button b4 = new Button("Left");
    Button b5 = new Button("Center");
    p1 add(b1, BorderLayout.NORTH);
    p1.add(b1, BorderLayout.SOUTH);
    p1.add(b3, BorderLayout.EAST);
    p1.add(b4, BorderLayout.WEST);
    p1.add(b5, BorderLayout.CENTER);
  }
}


You can use the constant values of BorderLayout to specify component positions.

These values can be BorderLayout.NORTH, BorderLayout.SOUTH, BorderLayout.EAST, BorderLayout.WEST, or BorderLayout.CENTER.

Within the confines of the container, the North, South, East, and West components get laid out according to their preferred sizes. The center component then occupies any remaining space.

Here is the code again.

import java.awt.*;
import java.applet.Applet;

public class DemoBorderLayout extends Applet {
  public void init () {
    Panel p1 = new Panel();
    //set layout for panel p1
    p1.setLayout (new BorderLayout());
    Button b1 = new Button("Top");
    Button b2 = new Button("Bottom");
    Button b3 = new Button("Right");
    Button b4 = new Button("Left");
    Button b5 = new Button("Center");
    p1 add(b1, BorderLayout.NORTH);
    p1.add(b1, BorderLayout.SOUTH);
    p1.add(b3, BorderLayout.EAST);
    p1.add(b4, BorderLayout.WEST);
    p1.add(b5, BorderLayout.CENTER);
  }
}


A BorderLayout manager is useful when you want to display standard borders on frames. You can make the center component a panel into which you place all the remaining subcomponents, using another layout manager to manage their layout.

BorderLayout, like GridLayout, can be used when you require the maximum space possible for a component.
CardLayout
The CardLayout class manages components so that only one component is displayed at any given time.

The code for implementing CardLayout in a panel is

Panel card = new Panel ();
card.setLayout(new CardLayout());


You can use methods such as first, last, next, and previous to select the current components to be displayed.

The syntax for the first, last, next, or previous method is

public void first (Container parent)
public void last (Container parent)
public void next (Container parent)
public void previous (Container parent)

The components in a CardLayout layout can, in turn, be containers that hold other components arranged with other layout managers.

This scheme is ideal for creating a tabbed dialog box or a set of properties sheets.

Here is the code again.

Panel card = new Panel ();
card.setLayout(new CardLayout());

Layout concepts

Specifying the position of onscreen components in GUIs can be repetitious for programmers. Sound principles to bear in mind when designing a GUI are
  • ease of use
  • logical positioning
  • grouping
Object-oriented programming enables the functionality associated with laying out components to be incorporated into a class.
The appearance of Swing components is independent of the host platform. Swing comes with its own decorations – which allow its components to achieve a uniform look and feel across platforms.
Java enables you to create a screen layout that is consistent across different platforms, without having to specify absolute positioning.
Each layout manager ensures that components will be laid out in a reasonable way, regardless of platform. Layout managers allow you to make intelligent suggestions about layout, but cannot guarantee exact results across all platforms.
Java provides layout manager classes that deal with onscreen layout. These include
  • the original set of layout managers
  • new layout classes
the original set of layout managers
The original layout managers date from the Java Development Kit (JDK) 1.0 and are

  • FlowLayout
  • GridLayout
  • GridBagLayout
  • BorderLayout
  • CardLayout
new layout classes
New layout classes are continually being added. The newer layout classes include

  • BoxLayout
  • OverlayLayout
  • ScrollPanelLayout
  • SpringLayout
  • ViewportLayout
The layout manager classes implement the interface java.awt.LayoutManager and are used in conjunction with containers.
The java.awt.Component class is an abstract class, so it cannot be instantiated.

However, three of its derived concrete classes – Window, Applet, and Panel – play vital roles in constructing a graphical interface.
A complex GUI can consist of an applet or frame divided into different sections – normally panels. The panels can incorporate components such as labels, entry fields, and buttons.
A GUI can consist of panels contained within other panels, and each panel can use its own layout manager.
After you create a container, you associate a layout manager with the container by passing an instance of a specific layout manager object as an argument to the container's setLayout method.
You can then add mutually exclusive components. For example, you can add a label called l1 and add the text you wish to display as a parameter.
import java.awt.* ;
import java.applet.Applet;

public class NewApplet extends Applet {
  public void init () {
    Panel p1 = new Panel ();
    //set layout for panel p1
    p1.setLayout (new BorderLayout ());
    Label l1 = new Label ("First Name: ");
    TextField t1 = new TextField (12);
    Label l2 = new Label ("Last Name: ");
    TextField t2 = new TextField (12);
    p1.add(l1);
    p1.add(t1);
    p1.add(l2);
    p1.add(t2);
  }
}
If you use the add method to place components in a container, you need to know which layout manager is being used by that container.
Certain layout managers, such as BorderLayout, may require you to pass the component's relative location within the container as an argument.
import java.awt.* ;
import java.applet.Applet;

public class NewApplet extends Applet {
  public void init () {
    Panel p1 = new Panel ();
    //set layout for panel p1
    p1.setLayout (new BorderLayout ());
    Label l1 = new Label ("First Name: ");
    TextField t1 = new TextField (12);
    Label l2 = new Label ("Last Name: ");
    TextField t2 = new TextField (12);
    p1.add(l1);
    p1.add(t1);
    p1.add(l2);
    p1.add(t2);
  }
}

Creating a menu

Swing enables you to create menus, menu bars, and menu items for applications, using the subclasses of the JComponent and JAbstractButton classes.
A menu enables users to choose one of several options. There are two types of menus:
  • menu bar
  • pop-up
menu bar
A menu bar contains one or more menus and is usually placed at the top of a window.
pop-up
A pop-up - shortcut - menu appears only when you perform a mouse action, such as clicking the right mouse button.
Swing contains several menu-related components:
  • menu bars
  • menus
  • menu items
  • radio button menu items
  • checkbox menu items
  • separators
The menu-related classes - JMenuBar, JPopUpMenu, and JSeparator - inherit directly from the JComponent class.
The JMenuBar class enables you to create a menu bar.
JMenuBar menuBar = new JMenuBar() ;
After you create a menu bar, you can add menu items to it. Menu items are buttons that can display text or an image, or both.

Because a menu is a button, it displays menu items by automatically bringing up a pop-up menu when activated.
You can add menu items to menus using the following menu-related classes:
  • JMenu
  • JMenuItem
  • JCheckboxMenuItem
  • JRadioButtonMenuItem
JMenu
The JMenu class is a subclass of JMenuItem. You can create an empty menu, a menu that contains text, or a menu from a specific Action object.

The syntax for the constructor is

public JMenu()
public JMenu(String str)
public JMenu(Action act)
JMenuItem
The JMenuItem class inherits directly from the JAbstractButton class. You can create a menu item that displays text, an image, or both. You can also pass it an integer argument, which specifies the keyboard alternative to use. An Action parameter in the JMenuItem constructor sets the action for the menu item.


The syntax for the constructor is

public JMenuItem()
public JMenuItem(String st)
public JMenuItem(Icon ic)
public JMenuItem(String st, Icon ic)
public JMenuItem(String st, int in)
public JMenuItem(Action ac)
JCheckboxMenuItem
The JCheckboxMenuItem class inherits from the JMenuItem class. This class enables you to create a menu item that looks and acts like a checkbox. You can create a checkbox item and specify a text string, an icon, or both, for the menu item. You can also pass a boolean argument that indicates whether the checkbox is initially selected.

The syntax for the constructor is

public JCheckboxMenuItem()
public JCheckboxMenuItem(String str)
public JCheckboxMenuItem(Icon ico)
public JCheckboxMenuItem(String str, Icon ico)
public JCheckboxMenuItem(String str, boolean bool)
public JCheckboxMenuItem(String str, Icon ico, boolean bool)
JRadioButtonMenuItem
The JRadioButtonMenuItem class is a subclass of JMenuItem. You use this class to create a menu item that looks and acts like a radio button. When creating a radio button, you can specify a text string, an image, or both. You can also pass a boolean argument that indicates whether the radio button is initially selected.

The syntax for the constructor is

public JRadioButtonMenuItem()
public JRadioButtonMenuItem(String str)
public JRadioButtonMenuItem(Icon ico)
public JRadioButtonMenuItem(String str, Icon ico)
public JRadioButtonMenuItem(String str, boolean bool)
public JRadioButtonMenuItem(String str, Icon ico, boolean bool)
To create a menu, you need to perform the following steps:
  • create a menu bar
  • create a menu
  • add the menu to the menu bar
  • add menu items to the menu
Suppose you are creating a basic menu application with two drop-down menus - File and Edit. Both these menus contain text menu items.

You start by creating a menu bar to contain the menus.
public class UsingMenus {
  JTextArea display ;
  JScrollPane scroller ;

  public JMenuBar createMenuBar() {
    JMenuBar menuBar ;
    JMenu menu ;
    JMenuItem menuItem ;

    //Step 1: Create the menu bar
    menuBar = new JMenuBar() ;
Then you create a File menu.
    //Step 2: Build a menu and add to menu bar
    menu = new JMenu ("File") ;
You can now add the menu to the menu bar.
public class UsingMenus {
  JTextArea display ;
  JScrollPane scroller ;

  public JMenuBar createMenuBar() {
    JMenuBar menuBar ;
    JMenu menu ;
    JMenuItem menuItem ;

    //Step 1: Create the menu bar
    menuBar = new JMenuBar() ;
    
    //Step 2: Build a menu and add to menu bar
    menu = new JMenu ("File") ;

    //Step 3: Add the menu to the menu bar
MISSING CODE ;
You type menuBar.add(menu).
You use the add method of the JMenuBar class to add the menu to the menu bar.
public class UsingMenus {
  JTextArea display ;
  JScrollPane scroller ;

  public JMenuBar createMenuBar() {
    JMenuBar menuBar ;
    JMenu menu ;
    JMenuItem menuItem ;

    //Step 1: Create the menu bar
    menuBar = new JMenuBar() ;
    
    //Step 2: Build a menu and add to menu bar
    menu = new JMenu ("File") ;

    //Step 3: Add the menu to the menu bar
    menuBar.add(menu) ;
Next you create three menu items - New, Open, and Save - and add them to the File menu using the add method of the JMenu class.

You specify a keyboard alternative, as a second argument, for each menu item.
  public JMenuBar createMenuBar() {
    JMenuBar menuBar ;
    JMenu menu ;
    JMenuItem menuItem ;

    //Step 1: Create the menu bar
    menuBar = new JMenuBar() ;
    
    //Step 2: Build a menu and add to menu bar
    menu = new JMenu ("File") ;

    //Step 3: Add the menu to the menu bar
    menuBar.add(menu) ;

    //Step 4: Add menu items
    menuItem = new JMenuItem("New", KeyEvent.VK_N) ;
    menu.add(menuItem) ;
    menuItem = new JMenuItem("Open", KeyEvent.VK_O) ;
    menu.add(menuItem) ;
    menuItem = new JMenuItem("Save", KeyEvent.VK_S) ;
    menu.add(menuItem) ;

Note

The JMenu class also provides insert and remove methods that enable you to add an item at a particular position in a menu or to remove a menu item from a menu.
Once you've created the File menu, you create the Edit menu and add it to the menu bar.
//Step 2: Build a menu and add to menu bar
    menu = new JMenu ("File") ;

    //Step 3: Add the menu to the menu bar
    menuBar.add(menu) ;

    //Step 4: Add menu items
    menuItem = new JMenuItem("New", KeyEvent.VK_N) ;
    menu.add(menuItem) ;
    menuItem = new JMenuItem("Open", KeyEvent.VK_O) ;
    menu.add(menuItem) ;
    menuItem = new JMenuItem("Save", KeyEvent.VK_S) ;
    menu.add(menuItem) ;

    //Build second menu in the menu bar.
    menu = new JMenu("Edit") ;
    menuBar.add(menu) ;
Then you create two menu items - Find and Replace - and add them to the Edit menu using the add method of the JMenu class.
    menuItem = new JMenuItem("Find", KeyEvent.VK_F) ;
    menu.add(menuItem) ;
    menuItem = new JMenuItem("Replace", KeyEvent.VK_R) ;
    menu.add(menuItem) ;
You have now created a menu bar containing two menus with menu items.

Creating and adding buttons

Swing enables you to create buttons and add them to a GUI, using one of the subclasses of the AbstractButton class.
The subclasses of the AbstractButton class include
  • JButton
  • JCheckBox
  • JRadioButton
JButton
You use the JButton class to create an ordinary button. You can create a button with no constructor parameters, with a specified text string or image, or both. You can also use the constructor to create a button that gets its properties from a specified action.

The syntax for the constructor class includes

public JButton()
public JButton(String st, Icon ic)
public JButton(String st)
public JButton(Icon ic)
public JButton(Action ac)

You implement event handling in ordinary buttons using an action listener, which is informed each time a user clicks the button.
JCheckBox
You use the JCheckBox class to create checkboxes. You can create a checkbox with no constructor parameters, or you can specify a text string or an image, or both. You can also pass a boolean argument that indicates whether the checkbox is initially selected.

The syntax for the constructor includes

public JCheckBox()
public JCheckBox(String st)
public JCheckBox(Icon ic)
public JCheckBox(String st, Icon ic)
public JCheckBox(String st, Icon ic, boolean bool)

A checkbox generates an item event and an action event each time it is clicked. You usually listen for item events, as these enable you to determine whether an action selected or deselected the checkbox.
JRadioButton
You use the JRadioButton class to create individual radio buttons. You can create a radio button with no constructor arguments, or you can specify a text string or an icon, or both. You can also pass a boolean argument that indicates whether the radio button is initially selected.

The syntax for the constructor includes

public JRadioButton()
public JRadioButton(String st)
public JRadioButton(Icon ic)
public JRadioButton(String st, Icon ic)
public JRadioButton(String st, Icon ic, boolean bool)


You use the ButtonGroup class to create a group of buttons. In a group of radio buttons, by convention, only one button can be selected at a time.

The syntax for the constructor is

public ButtonGroup()

A radio button generates an action event each time a user clicks it. One or two item events also occur - one from the button that is selected and another from the button that is deselected. You usually implement an action listener to handle radio button clicks.
Suppose you're creating a user interface that contains three different types of buttons - a common button, a radio button, and a checkbox - and displays a different message each time the user clicks a button.

You first add a common button - with the text "A JButton" - to the interface.
Then you create an action listener to ensure that clicking the button generates a response on the interface.
    // Add a JButton
    commonButton = new JButton("A JButton") ;
    commonButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        label.setText("JButton clicked") ;
      }
    }) ;
Next you want to add a checkbox named checkBox to the interface and specify that it is initially unselected.
    // Add a JCheckBox
    checkBox = MISSING CODE("Order special deals", false) ;
    checkBox.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        if (checkBox.isSelected())
          label.setText("You will be receiving special deals") ;
        else
          label.setText("You have chosen not to
receive special deals") ;
      }
    }) ;
You type new JCheckBox.
After you create the checkbox, you add an action listener to handle the actions from the checkbox.
You use the isSelected method to check if the action event selected or deselected the checkbox.

If the user selects the checkbox, the text label - "You will be receiving special deals" - displays.
    // Add a JCheckBox
    checkBox = new JCheckBox("Order special deals", false) ;
    checkBox.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        if (checkBox.isSelected())
          label.setText("You will be receiving special deals") ;
        else
          label.setText("You have chosen not to
receive special deals") ;
      }
    }) ;
Next you want to create a set of radio buttons that enables a user to choose a particular ice cream flavor - vanilla, chocolate, or strawberry.
So you create an instance of the ButtonGroup class, named icecreams, which you use to organize individual radio buttons. Then you create a radio button for each ice cream flavor - labeled "Vanilla", "Chocolate", and "Strawberry".
You set the action command string for each radio button using the setActionCommand method, which enables you to attach a string to an action within a generic event handler, for identification purposes.
You add an action listener for the radio buttons to detect when each is clicked.
    // Add a ButtonGroup to hold three radio buttons
    icecreams = new ButtonGroup() ;

    radio1 = new JRadioButton("Vanilla") ;
    radio1.setActionCommand("Vanilla") ;
    myRadioListener listenIn = new myRadioListener() ;
    radio1.addActionListener(listenIn) ;

    radio1.setSelected(true) ;
    radio2 = new JRadioButton("Chocolate") ;
    radio2.setActionCommand("Chocolate") ;
    radio2.addActionListener(listenIn) ;
    radio3 = new JRadioButton("Strawberry") ;
    radio3.setActionCommand("Strawberry") ;
    radio3.addActionListener(listenIn) ;

    icecreams.add(radio1) ;
    icecreams.add(radio2) ;
    icecreams.add(radio3) ;

    // A JPanel will hold the contents
    JPanel radiopane = new JPanel(new GridLayout(3,1)) ;
    radiopane.add(radio1) ;
    radiopane.add(radio2) ;
    radiopane.add(radio3) ;
You add the radio buttons to the button group using the add method of the ButtonGroup class.
void add(AbstractButton ab)
And you use the setSelected method so that the Vanilla radio button is initially selected.
    // Add a ButtonGroup to hold three radio buttons
    icecreams = new ButtonGroup() ;

    radio1 = new JRadioButton("Vanilla") ;
    radio1.setActionCommand("Vanilla") ;
    myRadioListener listenIn = new myRadioListener() ;
    radio1.addActionListener(listenIn) ;

    radio1.setSelected(true) ;
    radio2 = new JRadioButton("Chocolate") ;
    radio2.setActionCommand("Chocolate") ;
    radio2.addActionListener(listenIn) ;
    radio3 = new JRadioButton("Strawberry") ;
    radio3.setActionCommand("Strawberry") ;
    radio3.addActionListener(listenIn) ;

    icecreams.add(radio1) ;
    icecreams.add(radio2) ;
    icecreams.add(radio3) ;

    // A JPanel will hold the contents
    JPanel radiopane = new JPanel(new GridLayout(3,1)) ;
    radiopane.add(radio1) ;
    radiopane.add(radio2) ;
    radiopane.add(radio3) ;
You have now created an interface that contains a standard button, a checkbox, and a set of three radio buttons.

Creating labels and text

The Swing API provides classes and methods that enable you to create and add images and non-interactive text to an application.
You use the JLabel class to create and display non-interactive text and images.
You can create an instance of the JLabel class using the constructor with no arguments, or you can specify a string or an icon, or both.


public JLabel()
public JLabel(String st)
public JLabel(Icon ic)
public JLabel(String st, Icon ic)


You can also pass the JLabel constructor an int argument that specifies the horizontal alignment of the contents of the label. The integer argument can have one of the constant values - LEFT, CENTER, RIGHT, LEADING, or TRAILING - defined in the SwingConstants interface.


public JLabel(String st, int num)
public JLabel(Icon ic, int num)
public JLabel(String st, Icon ic, int num)


After you create a label, you can place text and images in it. You can do this using the setText, getText, setIcon, and getIcon methods of the JLabel class.


public void setText(String text)
public String getText()

public void setIcon(Icon image)
public Icon getIcon()



You can also use the following methods to set the alignment of a label's contents:
  • setHorizontalAlignment
  • getHorizontalAlignment
  • setVerticalAlignment
  • getVerticalAlignment

public void setHorizontalAlignment(int halign)
public int getHorizontalAlignment()

public void setVerticalAlignment(int valign)
public int getVerticalAlignment()


Suppose you are writing an application with a user interface that has a number of radio buttons and a label.

The text of the label indicates which radio button is selected.
You use the JLabel constructor to create a new label that contains an empty string. You then add the label to the pane.

//Create and add a label
label = new JLabel("    ") ;
pane.add(label, BorderLayout.CENTER) ;

You use the setText method to set the label's text to indicate
which radio button a user selected.

class myRadioListener implements ActionListener{
  public void actionPerformed(ActionEvent e) {
    label.setText(icecreams.getSelection().getActionCommand()) ;
  }
 


Question
Suppose you're writing an application that needs a label that contains the string "Hello" on the user interface.
Complete the code to create the label.

label = MISSING CODE ; pane.add(label, BorderLayout.CENTER) ;
 

Answer

To create the label, you use the code
 
new JLabel("Hello")
 
You use one of Swing's text components to display text and enable users to edit it. Swing's text components enable users to create the following categories of text areas:
  • text controls that can display and edit only one line of text
  • plain text areas that can display multiple editable lines of text
  • styled text components that can display and edit text using more than one font, and sometimes allow embedded images and components
Swing provides six text components, all of which inherit from the JTextComponent superclass.
  • JTextField
  • JPasswordField
  • JFormattedTextField
  • JTextArea
  • JEditorPane
  • JTextPane
JTextField
You use text fields - also known as text controls - to obtain a small amount of text from the user and perform an action once the text entry is complete. Text fields generate action events in the same way as buttons. For example, to log on to your computer, you enter your username. The system logs you in after you've entered your username.

You can create JTextField with no constructor parameters, or you can specify an initial string or the width of the field as an integer, or you can specify both.

The syntax for the constructor includes


public JTextField()
public JTextField(String text)
public JTextField(int size)
public JTextField(String text, int size)
 
JPasswordField
JPasswordField is a subclass of the JTextField class and as such is also a text control. For security purposes, this field does not display the characters that a user enters.

You can create a JPasswordField using a constructor with no arguments, or you can specify an initial string or an initial field size as an integer, number of columns, or both.

The syntax for the constructor includes


public JPasswordField()
public JPasswordField(String text)
public JPasswordField(int size)
public JPasswordField(String text, int size
 


JFormattedTextField
JFormattedTextField is a subclass of the JTextField class that enables you to specify a set of characters that users can enter into a text field. For example, you can specify the order in which users should enter the date - such as yy/mm/dd.

JFormattedTextField has an object value and a formatter that translates the field's value into the text displayed. You can create a JFormattedTextField using a constructor with no arguments, or you can specify an object value, a Format object, or an AbstractFormatter.

The syntax for this constructor includes

public JFormattedTextField()
public JFormattedTextField(Object val)
public JFormattedTextField(Format obj)
public JFormattedTextField(AbstractFormatter abs)
 
JTextArea
You can use JTextArea to display multiple lines of text in any font but all the text in the area must be in the same font. You can use a text area to display unformatted help information or to enable unformatted text of any length to be entered by users.

You can create a JTextArea using a constructor with no arguments, or you can specify an initial string or the width and height of the text area using an integer, number of columns, and rows, respectively. You can also specify both the string and the dimensions of the text area.

The syntax for the constructor includes
public JTextArea()
public JTextArea(String text)
public JTextArea(int width, int height)
public JTextArea(String text, int width, int height)

JEditorPane
The JEditorPane is a styled text component that can display and edit text using more than one font. The JEditorPane knows how to read, write, and edit plain text, HTML, and Rich Text Format (RTF) text. Editor panes are useful for displaying uneditable help information because they can be easily loaded with formatted text from a URL.

You can create a JEditorPane using a constructor that specifies the URL from which to load formatted text, or you can specify a string. If the referenced HTML or RTF file includes images, those images will be displayed in the Editor pane.

A simple web browser can easily be built using JEditorPane.

The syntax for the constructor includes



public JEditorPane(URL)
public JEditorPane(String text)

JTextPane
JTextPane is a subclass of JEditorPane and, as such, is a styled text component. You can use JTextPane to graphically represent attributes within a text component. Images and even components can be displayed in a text pane.

You can create a JTextPane using a constructor with no arguments, or you can specify the text pane's model.

A simple word processor can easily be built using JTextPane.

The syntax for the constructor includes
public JTextPane()
public JTextPane(StyledDocument model)


Suppose you're creating a user interface that contains a text field, a password field, a formatted text field, and a text area.

You've declared a JLabel called label, a JTextField called confirm, a JPasswordField called pass, a JFormattedTextField called format, and a JTextArea, called area.

To create the password field, you create an instance of JPasswordField - called pass - and you specify the length of the field - in this case, 20 columns wide.

 
You also create an instance of JTextField - confirm - that displays the password for a user to confirm. Once the password is confirmed, it is displayed in the text area. When creating this instance, you also specify the size of the field.


// A JPanel will hold the contents
  JPanel pane = new JPanel(new GridLayout(4,1)) ;

  confirm = new JTextField (25) ;
  pass = new JPasswordField(20) ;
  format = new JFormattedTextField(DateFormat.getDateInstance()) ;
  format.setValue(new Date()) ;
  format.setEnabled(false) ;
  area = new JTextArea(10, 20) ;

  pane.add(confirm) ;
  pane.add(pass) ;
  pane.add(format) ;
  pane.add(area) ;

        pass.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
      confirm.setText(new String(pass.getPassword())) ;
    }
  }) ;

        confirm.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
       area.setText(area.getText() + '\n' + confirm.getText()) ;
    }
  }) ;
 

You want the interface to contain a formatted text area that displays the date.

So you create an instance of JFormattedTextField that has the format of a Date object, DateFormat.
Next you use the setValue method of JFormattedTextField to set the value to be formatted in this format.

Then you use the setEnabled method and pass the boolean literal value of false as a parameter to the method to disable the text field so that users cannot edit it.


// A JPanel will hold the contents
  JPanel pane = new JPanel(new GridLayout(4,1)) ;

  confirm = new JTextField (25) ;
  pass = new JPasswordField(20) ;
  format = new JFormattedTextField(DateFormat.getDateInstance()) ;
  format.setValue(new Date()) ;
  format.setEnabled(false) ;
  area = new JTextArea(10, 20) ;

  pane.add(confirm) ;
  pane.add(pass) ;
  pane.add(format) ;
  pane.add(area) ;

        pass.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
      confirm.setText(new String(pass.getPassword()));
    }
  }) ;

        confirm.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
       area.setText(area.getText() + '\n' + confirm.getText()) ;
    }
  }) ;

The interface needs to contain a plain text area, so you create an instance of JTextArea - area - and specify the number of rows and columns.


// A JPanel will hold the contents
  JPanel pane = new JPanel(new GridLayout(4,1)) ;

  confirm = new JTextField (25) ;
  pass = new JPasswordField(20) ;
  format = new JFormattedTextField(DateFormat.getDateInstance()) ;
  format.setValue(new Date()) ;
  format.setEnabled(false) ;
  area = new JTextArea(10, 20) ;

  pane.add(confirm) ;
  pane.add(pass) ;
  pane.add(format) ;
  pane.add(area) ;

        pass.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
      confirm.setText(new String(pass.getPassword())) ;
    }
  }) ;

        confirm.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
       area.setText(area.getText() + '\n' + confirm.getText()) ;
    }
  }) ;


You use the addActionListener method to add an action listener to the password field - pass - so that it can receive and respond to action events.
And you use the getPassword method of JPasswordField in the actionPerformed method of the password field's ActionListener to return the text of the password field as a string and display it in the confirm text field.



// A JPanel will hold the contents
  JPanel pane = new JPanel(new GridLayout(4,1)) ;

  confirm = new JTextField (25) ;
  pass = new JPasswordField(20) ;
  format = new JFormattedTextField(DateFormat.getDateInstance()) ;
  format.setValue(new Date()) ;
  format.setEnabled(false) ;
  area = new JTextArea(10, 20) ;

  pane.add(confirm) ;
  pane.add(pass) ;
  pane.add(format) ;
  pane.add(area) ;

        pass.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
      confirm.setText(new String(pass.getPassword()));
    }
  });

        confirm.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
       area.setText(area.getText() + '\n' + confirm.getText()) ;
    }
  }) ;

You add an action listener to the confirm field so that it can respond when text is entered into it.
You use the getText and setText methods of JTextComponent in the actionPerformed method of the action listener for confirm. This will add the password, as a string, to the text already displayed in the text area.


// A JPanel will hold the contents
  JPanel pane = new JPanel(new GridLayout(4,1)) ;

  confirm = new JTextField (25) ;
  pass = new JPasswordField(20) ;
  format = new JFormattedTextField(DateFormat.getDateInstance()) ;
  format.setValue(new Date()) ;
  format.setEnabled(false) ;
  area = new JTextArea(10, 20) ;

  pane.add(confirm) ;
  pane.add(pass) ;
  pane.add(format) ;
  pane.add(area) ;

        pass.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
      confirm.setText(new String(pass.getPassword())) ;
    }
  }) ;

        confirm.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
       area.setText(area.getText() + '\n' + confirm.getText()) ;
    }
  }) ;


When you run the code, the application's GUI displays the four text areas.