Monday, February 13, 2012

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());