Showing posts with label Swing Components. Show all posts
Showing posts with label Swing Components. Show all posts

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.

Friday, February 10, 2012

Swing components and containers

Swing components and container objects

In Java, a component is the basic user interface object and is found in all Java applications. Components include lists, buttons, panels, and windows.

To use components, you need to place them in a container.
A container is a component that holds and manages other components. Containers display components using a layout manager.
Swing components inherit from the javax.Swing.JComponent class, which is the root of the Swing component hierarchy. JComponent, in turn, inherits from the Container class in the Abstract Windowing Toolkit (AWT). So Swing is based on classes inherited from AWT.
Swing provides the following useful top-level containers, all of which inherit from JComponent:


JWindow
JWindow is a top-level window that doesn't have any trimmings and can be displayed anywhere on a desktop. JWindow is a heavyweight component. You usually use JWindow to create pop-up windows and "splash" screens. JWindow extends AWT's Window class.
JFrame
JFrame is a top-level window that can contain borders and menu bars. JFrame is a subclass of JWindow and is thus a heavyweight component. You place a JFrame on a JWindow. JFrame extends AWT's Frame class.
JDialog
JDialog is a lightweight component that you use to create dialog windows. You can place dialog windows on a JFrame or JApplet. JDialog extends AWT's Dialog class.
JApplet
JApplet is a container that provides the basis for applets that run within web browsers. JApplet is a lightweight component that can contain other graphical user interface (GUI) components. JApplet extends AWT's Applet class.

All Swing components - including the JApplet and JDialog containers - need to be contained at some level inside a JWindow or JFrame.
Each top-level container depends on another intermediate container called the root, which provides a number of components to each.

JApplet is the root container for Swing applets and JFrame is the root container for a standalone GUI application.

Once you've created a root container, you can add components and other containers to it.

Each top-level container consists of the following panes:

Root pane
The root pane is an intermediate container that manages the layered pane, content pane, and glass pane. It can also manage an optional menu bar. You use a root pane to paint over multiple components or to catch input events.
 
Layered pane
The layered pane contains the content pane and the optional menu bar. It can also contain other components, which it arranges so that they overlap each other. This enables you to add pop-up menus to applications. The layered pane provides six functional layers in which you place the components you add to it. You use each of these functional layers for a specific function.
 
Content pane
The content pane holds all the visible components of the root pane, except the menu bar. It covers the visible section of the JFrame or JWindow and you use it to add components to the display area. Java automatically creates a content pane when you create a JFrame or JWindow but you can create your own content pane, which has to be opaque.
 
Glass pane
The glass pane is invisible by default but you can make it visible. When it is visible, it covers the components of the content pane, blocks all input events from reading these components, and can paint over an existing area containing one or more components.

One of the enhancements to JTabbedPane is the use of a component to represent the tab in a JTabbedPane. This new feature offers a convenient way to show several items in a small amount of space. It does this by dividing the information across separate tabs so that a user can select
  • one tab to list a particular set of components
  • a different tab to list a different set of components
By adding a Close button, you can enable the removal of the current tab from JTabbedPane.


JComponent services

JComponent is the root class for all Swing components such as JPanel, JLabel, and JButton. This class inherits from the Container class and enables you to add containers and components to an application.

The JComponent class provides the following functionality features to its subclasses:
  • Customizing component appearance
  • Checking component states
  • Adding event handling
  • Painting components
  • Modifying the containment hierarchy
  • Arranging the layout of components
  • Retrieving component size and position information
  • TextComponent Printing
Customizing component appearance
You can change the appearance of a component by setting the border, foreground color, background color, font, and a cursor to display when moving over the component.

The most commonly used methods to change the appearance of a component include the setForeground and setBackground methods, which enable you to set the colors for a component.

The setForeground method sets the color for a component's text and the setBackground method sets the color for the background areas of a component.

You can also set a component to be opaque.

For example, consider the code used to change the background color of a JLabel - called label - to black.

The code to change the background color of a label is

label.setBackground(Color.black);
 
Checking component states
The JComponent class enables you to determine the state of components.

You can add tooltips and specify names for components, using the setToolTipText and setName methods, respectively.

You can also use the isEnabled method to check whether a component is enabled to generate events from user input.

You can set a component to be visible using the setVisible method.

You can also determine whether a component is visible onscreen by using the isShowing method.
 
Adding event handling
The JComponent class provides methods that enable you to add and remove event listeners for mouse clicks, mouse movements, key presses, or component changes.

These methods include addMouseListener, addMouseMotionListener, addKeyListener, and addComponentListener.

JComponent provides a method - setTransferHandler - that you can use to enable the transfer of data using the Drag-and-Drop feature or via cut, copy, or paste functions.

You can check which component contains a specific point using the contains method. You can also determine which component lies at a specified position using the getComponentAt method.
 
Painting components
JComponent provides methods that enable you to customize painting for all its subclasses.

You can use the repaint method to repaint a component or a specific part within it.

You can refresh the layout of a component and its associated containers using the revalidate method.

However, you usually invoke this method if you change the containment hierarchy or the size of a component.
 
Modifying the containment hierarchy
You can add or remove one or more components to a container using the add and remove methods, respectively.

When adding or removing a component, you can specify the component's position in the container using the add method with an int argument. If you do not specify a component's position, it is placed at the end of the container.
 
Arranging the layout of components
You can add or remove components from a container using a layout manager or absolute position.

To specify a layout manager, you can use the setLayout and getLayout methods.

You can also specify a preferred, maximum, or minimum size of any Component object, using the setPreferredSize, setMaximumSize, and setMinimumSize methods, respectively.

Some layout managers will respect the preferred size, such as FlowLayout. Other Layout managers will ignore the preferred size, such as BorderLayout. So setting the preferredSize may not automatically yield the desired result in component size, because the layout manager will have an effect on the component sizes.

Using the layout manager enables you to set the alignment and orientation of a component. When using an absolute position, you can specify a component's location or size. To do this, you can use the setLocation and setSize methods, respectively.

You can also set the location and size using just one method, setBounds, which takes four integer parameters.
 
Retrieving component size and position information
You can retrieve information about the current width, height, size, and position of a component. To do this, you can use separate methods - getWidth, getHeight, getSize, and getLocation - or you can use the getBounds method, which retrieves all this information simultaneously.

JComponent provides a method - getInsets - that enables you to retrieve information about a component's border size.
 
TextComponent Printing
Java SE 6 simplifies the printing of the different JTextComponent elements. JTextField, JTextArea, and JTextPane contents can now be printed without any concern about pagination. This is now performed using any of the three new print methods added to the JTextComponent class.

The three new print methods are as follows:
 

 
The MessageFormat class enables you to produce concatenated messages in a language-neutral way. You should use this class to construct messages displayed for end users, that would incorporate headers and footers.
 


The printDialog method displays a dialog box and returns true if the user selects OK and false if they select Cancel. You would use this method to determine whether to attempt to print.



PrintService is an interface used to describe the capabilities of a Printer object. Using this interface, you can query the printer's supported attributes.

Attributes specifies the formats to be applied to the print job – such as double spaced or border sizes.

Interactive is used to display the current progress of a print job as well as a means to abort the current print job.


Using components and containers

All Swing applications have a containment hierarchy with a top-level container at its root to which you can add components.

For example, you can create a dialog within a JFrame container by adding a JDialog container to it via a content pane.
You use the add method to add components to all containers except JFrame and JWindow.
To add components to JFrame or JWindow, you need to add the components to the container's content pane. To do this, you retrieve the container's content pane using the getContentPane method.
Once you've added a component to a container, you need to make it visible. To do this, you use the setVisible method.
You can check whether a component is visible by using the isVisible method.
After you add components to a container, you can
  • set their size
  • specify the focus
set their size
You can use the setSize method to specify an absolute size for the component. You can also have a frame or window adjust automatically to fit all its elements by using the pack method, which ensures that the container is not smaller than its component's preferred size.
 
specify the focus
If users can interact with interface items using the mouse and keyboard, you need to ensure that the items can receive keyboard focus. By default, most components can receive focus, but you can specify this using the setFocusable method. You can also use the requestFocus method to request that a component receives focus.

Suppose that you're creating a Swing application that contains a button, a checkbox, and three radio buttons. This application prints a different message each time a user clicks one of these items.


You start by importing the Swing and AWT packages.

Next you declare a JButton called commonButton, a checkbox, a ButtonGroup called icecreams that contains the three radio buttons, and the radio buttons - radio1, radio2, and radio3.

A JButton is the Swing equivalent of a Button in AWT. It is used to provide an interface equivalent of a common button.

A JCheckBox is the Swing equivalent of the Checkbox component in AWT. This is sometimes called a ticker box, and is used to represent multiple option selections in a form.

A JRadioButton is the swing equivalent of a RadioButton in AWT. It is used to represent multiple option single selection elements in a form. This is performed by grouping the JRadio buttons using a ButtonGroup component.
You create a JFrame called frame and a JPanel - pane - to hold the contents.
Then you add a JButton. You use an action listener to determine whether the button is clicked.


Next you create the three radio buttons, add action listeners for each, and add them to the ButtonGroup.



You then create a new JPanel - radiopane - which contains the three radio buttons. Then you add the button, checkbox, and the radiopane to the pane.
And you set the focus on the commonButton button using the requestFocus method.


You create an empty JLabel named label to hold and display the message that is printed when the user clicks one of the components. You use the add method to add the label to the JPanel.


You can now add the JPanel to the JFrame. To do this, you add the JPanel to the frame's content pane.


 

You type frame.
You use the getContentPane method with the add method to add the JPanel to the JFrame. Although you can still use the getContentPane method to retrieve a java.awt.Container object, and add other components to the Container object, in Java SE 6.0 you can also call the add(Component) method against the JFrame object directly.

 


You can set the width and height of the frame by calling the setSize method. In this case, you set the width to 300 pixels and the height to 200 pixels.
And you can display the frame by setting the setVisible method to true.



You've now created a Buttons application that contains a button, a checkbox, and three radio buttons.


Creating a basic Swing application

When creating a GUI application, you can determine the look and feel of windows and frames in the application.

You need to set the look and feel for a frame before you create it. This setting affects all subsequently created JFrame.

You can customize the decoration of windows and frames in an application by using the setDefaultLookAndFeelDecorated method - a static method in the JFrame class - with a true value.

You can specify custom settings, enable full-screen exclusive mode, remove all decorations, or set an icon to represent a window.

You can also specify how each window reacts when a user clicks the Close button.
To determine what happens when a user clicks the Close button, you use the setDefaultCloseOperation method with one of the following values as an argument:
  • HIDE_ON_CLOSE
  • EXIT_ON_CLOSE
  • DISPOSE_ON_CLOSE
  • DO_NOTHING_ON_CLOSE
HIDE_ON_CLOSE
The HIDE_ON_CLOSE parameter hides the frame but doesn't exit the window. This is the default setting for JFrame and JDialog.
 
EXIT_ON_CLOSE
You use EXIT_ON_CLOSE to exit an application using the System.exit method. This value is useful for applications - especially applications with only one frame - but cannot be used with applets.
 
DISPOSE_ON_CLOSE
Specifying the DISPOSE_ON_CLOSE parameter hides the frame and frees up any resources used by it. This is the default setting for internal frames.
 
DO_NOTHING_ON_CLOSE
When you specify the DO_NOTHING_ON_CLOSE parameter, the application performs actions specified in the windowClosing method of the WindowListener object.
Event handling in Swing executes in a single thread - the event-dispatching thread. This thread ensures that event handlers are not interrupted while they are executing.
Suppose that you're building a Swing application with only one frame and one button. The application also ensures that the window exits when a user clicks the Close button.

To build a basic application, you
  • import the necessary packages
  • create and customize a top-level container and its components
  • ensure thread safety
You start by including the relevant packages. You import all the Swing classes.
Because most Swing components inherit from AWT classes, you import the awt package. You also want the application to support event handling, so you include all the AWT classes for events.



 




In the BasicSwing class, you create a createGUI method that contains the code to create and customize the top-level container, add components, and display the container.

You want the windows to use the default look and feel, so you set the setDefaultLookAndFeelDecorated method to true.
Then you create the JFrame called frame.





















After you create the JFrame, you want to ensure that the window exits when a user clicks the Close button. To do this, you use the setDefaultCloseOperation method.


 




















You type JFrame.EXIT_ON_CLOSE and press Enter.

Using the EXIT_ON_CLOSE parameter with the setDefaultCloseOperation method ensures that the window exits when the Close button is clicked.























Next you create a JPanel and a JButton. You use the JPanel to hold the contents of the container. And you add the button to the JPanel.
After adding the button to the pane, you add the JPanel to the frame.






























Once you've added the components to the top-level container, you can set its size to 220 by 200 pixels and make it visible onscreen. To do this, you use the setSize and setVisible methods, respectively.






























Once you've created and customized the container and its components, you create a main method to run and display the GUI.






























To avoid threading issues when creating and displaying the application's GUI, you want to ensure that code in the main method is executed within the event-dispatching thread.

































You type SwingUtilities.invokeLater.

You use the invokeLater method to ensure that the GUI is created on the event-dispatching thread.

You then pass a Runnable object inside the invokeLater method.

In the Runnable class, you create an instance of the BasicSwing class - called app - in the run method.

You use this instance to invoke the createGUI method.


 













 

Summary

In Java, graphical user interfaces (GUIs) consist of components and containers. Components are basic user interface objects that are contained and managed in a container. Swing is a Java-based GUI toolkit whose components are based on classes from the Abstract Windowing Toolkit (AWT).

All Swing components inherit from the JComponent class, which is a subclass of the Container class. The JComponent class enables you to customize the appearance of components, check component states, add event handling, paint components, modify the containment hierarchy, arrange the layout of components, and retrieve component size and position information.

You can add components to a container using the add method. To add components to a JFrame or JWindow, you use the getContentPane method because you add the components to the content pane. Once you've added components to a container, you use the setVisible method to make the container appear onscreen.

To build a basic Swing application, you import the necessary packages, create and customize a top-level container and components, and ensure thread-safety. You can customize windows and frames using the setDefaultLookAndFeelDecorated method. You can also determine what happens when users close windows, using the setDefaultCloseOperation method.