Components and Containers in AWT

Scenario for building a GUI

  1. Create the frame.
    JFrame guiFrame = new JFrame ("A Frame");
  2. Construct the component hierarchy by adding panels and other GUI control components.
    guiFrame.add ( new JButton ( "ON" ) );
  3. Set the size of the frame by using the inherited setSize() method.
    guiFrame.setSize ( 200, 300 );
  4. Pack the frame by calling the pack() method.
    guiFrame.pack ();
  5. Make the frame (and its constituents) visible by calling the setVisible() method.
    guiFrame.setVisible ( true );

GUI Control Components

GUI control components are the primary elements of a graphical user interface that enable interaction with the user. They are subclasses of the Component class. The GUI control components for constructing menus are derived from the abstract class MenuComponent.

The following three steps are essential in making use of a GUI control component.

  1. A GUI control component is created by calling the appropriate constructor.
    JButton guiComponent = new JButton ( "ON" );
  2. The GUI control component is added to a container using a layout manager. This involves invoking the overloaded method add() on a container with the GUI control component as the argument.
    guiFrame.add ( guiComponent );
  3. Listeners are registered with the GUI component, so that they can receive events when these occur. GUI components generate particular events in response to user actions.

Menu Components

The abstract class MenuComponent is the superclass of all menu-related classes. The MenuBar class implements a menu bar that can contain pull down menus. A menu bar can be attached to a Frame object. NOTE that an applet is not a subclass of the Frame class and cannot have a menu bar.

The MenuItem class defines a menu item that has a textual label. The Menu class implements a pull down menu that can appear in a menu bar. A Menu is a container of MenuItem objects. A menu item can be added using the add() method. A visible horizontal mark for organizing menu items into sections can be added using the addSeparator() method.

The PopupMenu class represents a pop-up menu that can be popped up at a specified position within a component, as opposed to a pull down menu. A pop-up menu cannot be contained in a menu bar.

The CheckboxMenuItem class implements a checkbox with a textual label that can appear in a menu. The menu checkbox toggles its state when clicked.

These are the steps to create a menu bar for a frame:

  1. Create a menu bar
    MenuBar foodBar = new MenuBar();
  2. Create a menu
    Menu pizzaMenu = new Menu ( "Pizza Menu" );
  3. Create menu items and add them to the menu. The menu items appear from top to bottom in the menu, according to the order in which they are added to the menu.
    pizzaMenu.add ( new MenuItem ( "Large Pan Pizza" ) );
    pizzaMenu.addSeparator();
    pizzaMenu.add ( new MenuItem ( "Medium Pan Pizza" ) );
    pizzaMenu.addSeparator();
    pizzaMenu.add ( new CheckboxMenuItem ( "Small Pan Pizza" ) );
    pizzaMenu.addSeparator();
    
  4. Add each menu to the menu bar. The menus appear from left to right in the menu bar, according to the order in which they are added to the menu bar.
    foodBar.add ( pizzaMenu );
  5. Add the menu bar to the frame.
    Frame fastFood = new Frame ( "Fast Food" );
    fastFood.setMenuBar ( foodBar );
    

This is sample code that shows how to use some of the GUI controls. The controls are laid out by the flow layout manager. This is a very simple layout process where the controls are placed from left to right. The controls towards the end of the row spill over to the next row if there is not enough space in the current row.


import java.awt.*;
import javax.swing.*;

public class GUIComponents
{ 
    
    public static void main ( String[] args )
    {
      JFrame frame = new JFrame ( "GUI Components" );
       
      // Create buttons
      JButton buttonA = new JButton ( "ON" );
      JButton buttonB = new JButton ( "OFF" );
        
      // Create a checkbox
      JCheckBox option = new JCheckBox ("Subscribe");
        
      // Create radio buttons or check box group
      ButtonGroup optionGroup = new ButtonGroup();
      JRadioButton cbTrue = new JRadioButton ("Accept");
      JRadioButton cbFalse = new JRadioButton ("Decline");
      optionGroup.add (cbTrue);
      optionGroup.add (cbFalse);
        
      // Create pull down menu
      JComboBox colorChoice = new JComboBox ();
      colorChoice.addItem ("Red");
      colorChoice.addItem ("Blue");
      colorChoice.addItem ("Yellow");
      colorChoice.addItem ("Green");
        
      // Create labels
      JLabel colors = new JLabel ("Colors");
      JLabel fruits = new JLabel ("Fruits");      
        
      // Create list    
      String fruit[] = {"Apple", "Orange", "Mango", "Banana", "Grape", "Melon"};
      JList fruitList = new JList (fruit);
           
      // Create scrollbar
      JScrollBar vBar = new JScrollBar (JScrollBar.VERTICAL, 0, 10, 0, 255);
      JScrollBar hBar = new JScrollBar (JScrollBar.HORIZONTAL, 0, 10, -127, 127);
        
      // Add Text Field
      JTextField entryField = new JTextField (20);
      entryField.setFont (new Font ("Times", Font.BOLD, 12));
      entryField.setText ("Enter a number");

      // Create Text Area
      JTextArea area = new JTextArea (3, 6);  // rows, columns
      area.setFont (new Font("Helvetica", Font.PLAIN, 12));
      area.setText ("Animal \n Bird \n Insect \n Fish \n");
      area.setEditable (false);

      // Create a menu
      JMenuBar foodBar = new JMenuBar ();
      
      JMenu soups = new JMenu ("Soups");
      soups.add ( new JMenuItem ( "Tomato" ) );
      soups.addSeparator();
      soups.add ( new JMenuItem ( "Chicken" ) );
      soups.addSeparator(); 
      soups.add ( new JMenuItem ( "French Onion" ) );
      soups.addSeparator(); 
      soups.add ( new JMenuItem ( "Clam Chowder" ) );
      foodBar.add ( soups );
      
      JMenu iceCream = new JMenu ("Ice Creams");
      iceCream.add ( new JMenuItem ( "Vanilla" ) );
      iceCream.addSeparator();
      iceCream.add ( new JMenuItem ( "Strawberry" ) );
      iceCream.addSeparator(); 
      iceCream.add ( new JMenuItem ( "Chocolate" ) );
      iceCream.addSeparator(); 
      iceCream.add ( new JMenuItem ( "Butter Pecan" ) );
      foodBar.add ( iceCream );
      
      frame.setJMenuBar ( foodBar );

      // Create and set the GridLayout
      frame.setLayout ( new FlowLayout () );
      
      frame.add ( colors );
      frame.add ( colorChoice );
      frame.add ( fruits );
      frame.add ( fruitList );
      frame.add ( buttonA );
      frame.add ( buttonB );
      frame.add ( option );
      frame.add ( cbTrue );
      frame.add ( cbFalse );
      frame.add ( entryField );
      frame.add ( area );
      frame.add ( vBar );
      frame.add ( hBar );
      
      frame.pack ();
      frame.setVisible ( true );
      
    }
        
}

Layout Managers

A layout manager implements a layout policy that defines spatial relationships between components in a container. Once a layout manager is registered with a container and components have been added, the layout manager is responsible for the placement and sizing of the components. Applications never call the methods of the layout manager directly. The container calls the appropriate methods in the layout manager when necessary. The Java AWT package provides five layout managers.

FlowLayout: Lays out the components in row-major order. Default layout manager for Applet classes. The FlowLayout class provides constructors that allow the alignment, horizontal, and vertical gaps for the layout to be specified

FlowLayout()
FlowLayout (int alignment)
FlowLayout (int alignment, int horizontalgap, int verticalgap)

GridLayout: Lays out the components in a specified rectangular grid. The GridLayout class provides the following constructors:

GridLayout()
GridLayout (int rows, int columns)
GridLayout (int rows, int columns, int horizontalgap, int verticalgap)

BorderLayout: Up to five components can be placed in a container in the following directions - north, south, east, west, and center. The default region is the center. The BorderLayout class has the following constructors:

BorderLayout()
BorderLayout (int horizontalgap, int verticalgap)

void add (Component comp, Object constraints)

CardLayout: Components are handled as a stack of indexed cards with only the top component being visible in the container. The CardLayout does not give any visual clue that the container consists of a stack of components. The CardLayout class has the following constructors:

CardLayout()
CardLayout (int horizontalgap, int verticalgap);

GridBagLayout: Customizable and flexible layout manager that lays out components in a rectangular grid. A component can occupy multiple cells in the grid but the region it occupies is always rectangular. To set up a GridBagLayout the following steps have to be taken:

  1. Create an object of the class GridBagLayout
    GridBagLayout gbl = new GridBagLayout();
  2. Set the layout manager for the container
    container.setLayout(gbl);
  3. Create an object of the class GridBagConstraints
    GridBagConstraints gbc = new GridBagConstraints();
  4. For each component to be added fill in the layout information in the GridBagConstraints object and add the component.
    Container.add (new Checkbox("Fill", false), gbc);

The key to using the grid bag layout is to understand how the GridBagConstraints object affects the layout. A GridBagConstraints object can be constructed using the following constructors:

GridBagConstraints()
GridBagConstraints (int gridx, int gridy, int gridwidth, int gridheight, 
		    double weightx, double weighty, int anchor, int fill, 
		    Insets insets, int ipadx, int ipady)

Common Methods for designing a Layout

Getting and setting a Layout Manager
	LayoutManager  getLayout()
	void setLayout (LayoutManager mgr)

Adding components

	Component add (Component comp)
	void add (Component comp, Object constraints)

Removing components

	void remove (Component comp)
	void removeAll ()

For simple applications, the components can be put directly into an applet or a single frame. However, components can be placed into containers, which in turn can be put into other containers, resulting in a component hierarchy. This should not be confused with inheritance hierarchy.