How to Use Buttons

 < Day Day Up > 

How to Use Buttons

To create a button, you can instantiate one of the many classes that descend from the AbstractButton [6] class. Table 2 shows the Swing-defined AbstractButton subclasses that you might want to use.

[6] AbstractButton API documentation: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/AbstractButton.html.

Table 2. Swing-Defined AbstractButton Subclasses

Class

Summary

Where Described

JButton

A common button.

How to Use the Common Button API (page 157) and How to Use JButton Features (page 159)

JCheckBox

A check box button.

How to Use Check Boxes (page 163)

JRadioButton

One of a group of radio buttons.

How to Use Radio Buttons (page 311)

JMenuItem

An item in a menu.

How to Use Menus (page 277)

JCheckBoxMenuItem

A menu item that has a check box.

How to Use Menus (page 277) and How to Use Check Boxes (page 163)

JRadioButtonMenuItem

A menu item that has a radio button.

How to Use Menus (page 277) and How to Use Radio Buttons (page 311)

JToggleButton

Implements toggle functionality inherited by JCheckBox and JRadioButton . Can be instantiated or subclassed to create two-state buttons.

Used in some examples listed in Examples That Use Buttons (page 162)

Note: If you want to collect a group of buttons into a row or column, then you should check out tool bars. You can read about them in How to Use Tool Bars (page 427) later in this chapter.


First, this section explains the basic button API that AbstractButton definesand thus what all Swing buttons have in common. Next, it describes the small amount of API that JButton adds to AbstractButton . After that, this section shows you how to use specialized API to implement check boxes and radio buttons.

How to Use the Common Button API

Figure 2 shows a picture of an application that displays three buttons.

Figure 2. The ButtonDemo application.

graphics/07fig02.jpg

Try This:

  1. graphics/cd_icon.gif

    Run ButtonDemo using Java Web Start or compile and run the example yourself. [7]

    [7] To run ButtonDemo using Java Web Start, click the ButtonDemo link on the RunExamples/ components .html page on the CD. You can find the source files here: JavaTutorial/uiswing/components/example-1dot4/index.html#ButtonDemo .

  2. Click the left button. It disables the middle button (and itself since it's no longer useful) and enables the right button.

  3. Click the right button. It enables the middle button and the left button, and disables itself.

As the ButtonDemo example shows, a Swing button can display both text and an image. In ButtonDemo , each button has its text in a different place, relative to its image. The underlined letter in each button's text shows the button's mnemonic the keyboard alternative. In most look and feels, the user can click a button by pressing the Alt key and the mnemonic. For example, Alt-M clicks the middle button in ButtonDemo .

When a button is disabled, the look and feel automatically generates the button's disabled appearance. However, you could provide an image to substitute for the normal imagefor example, gray versions of the images used in the left and right buttons.

How you implement event handling depends on the type of button you use and how you use it. Generally, you implement an action listener, which is notified every time the user clicks the button.

The code that follows is from ButtonDemo.java . It creates the buttons in the previous example and reacts to button clicks. The bold code is what would remain if the buttons had no images.

  //In initialization code:  ImageIcon leftButtonIcon = createImageIcon("images/right.gif");     ImageIcon middleButtonIcon = createImageIcon("images/middle.gif");     ImageIcon rightButtonIcon = createImageIcon("images/left.gif");  b1 = new JButton("Disable middle button"  , leftButtonIcon);     b1.setVerticalTextPosition(AbstractButton.CENTER);     b1.setHorizontalTextPosition(AbstractButton.LEADING);     //aka LEFT, for left-to-right locales  b1.setMnemonic(KeyEvent.VK_D);   b1.setActionCommand("disable");   b2 = new JButton("Middle button"  , middleButtonIcon);     b2.setVerticalTextPosition(AbstractButton.BOTTOM);     b2.setHorizontalTextPosition(AbstractButton.CENTER);  b2.setMnemonic(KeyEvent.VK_M);   b3 = new JButton("Enable middle button"  , rightButtonIcon);     //Use the default text position of CENTER, TRAILING (RIGHT).  b3.setMnemonic(KeyEvent.VK_E);   b3.setActionCommand("enable");   b3.setEnabled(false);  //Listen for actions on buttons 1 and 3.  b1.addActionListener(this);   b3.addActionListener(this);   b1.setToolTipText("Click this button to disable "   + "the middle button.");   b2.setToolTipText("This middle button does nothing "   + "when you click it.");   b3.setToolTipText("Click this button to enable the "   + "middle button.");  ... }  public void actionPerformed(ActionEvent e) {   if ("disable".equals(e.getActionCommand())) {   b2.setEnabled(false);   b1.setEnabled(false);   b3.setEnabled(true);   } else {   b2.setEnabled(true);   b1.setEnabled(true);   b3.setEnabled(false);   }   }  protected static ImageIcon createImageIcon(String path) {     java.net.URL imgURL = ButtonDemo.class.getResource(path);  ...//error handling omitted for clarity...  return new ImageIcon(imgURL); } 

How to Use JButton Features

Ordinary buttons JButton [8] objectshave just a bit more functionality than the AbstractButton class provides: You can make a JButton the default button.

[8] JButton API documentation: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JButton.html.

At most one button in a top-level container can be the default button. The default button typically has a highlighted appearance and acts clicked whenever the top-level container has the keyboard focus and the user presses the Enter key. Figure 3 is a picture of a dialog in which the Set button is the default button.

Figure 3. The ListDialog component.

graphics/07fig03.gif

You set the default button by invoking the setDefaultButton method on a top-level container's root pane. Here's the code that sets up the default button for the ListDialog example:

  //In the constructor for a JDialog subclass:  getRootPane().setDefaultButton(setButton); 

The exact implementation of the default button feature depends on the look and feel. For example, in the Windows look and feel, the default button changes to whichever button has the focus so that pressing Enter clicks the focused button. When no button has the focus, the button you originally specified as the default button becomes the default button again.

The Button API

Tables 3 through 5 list the commonly used button- related API. With the exception of the JButton constructors, all of the listed API is defined by the AbstractButton class. Other methods you might call, such as setFont and setForeground , are listed in the API tables in the section The JComponent Class (page 53) in Chapter 3. You should also refer to the API documentation for AbstractButton [9] and JButton . [10]

[9] AbstractButton API documentation: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/AbstractButton.html.

[10] JButton API documentation: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JButton.html.

Table 3. Setting or Getting the Button's Contents

Method or Constructor

Purpose

 JButton(Action) JButton(String, Icon) JButton(String) JButton(Icon) JButton() 

Create a JButton instance, initializing it to have the specified text/image/action. The JButton(Action) constructor was added to JButton in 1.3.

 void setAction(Action) Action getAction() 

Set or get the button's properties according to values from the Action instance. Introduced in 1.3.

 void setText(String) String getText() 

Set or get the text displayed by the button.

 void setIcon(Icon) Icon getIcon() 

Set or get the image displayed by the button when the button isn't selected or pressed.

 void setDisabledIcon(Icon) Icon getDisabledIcon() 

Set or get the image displayed by the button when it's disabled. If you don't specify a disabled image, the look and feel creates one by manipulating the default image.

 void setPressedIcon(Icon) Icon getPressedIcon() 

Set or get the image displayed by the button when it's being pressed.

 void setSelectedIcon(Icon) Icon getSelectedIcon() void setDisabledSelectedIcon(Icon) Icon getDisabledSelectedIcon() 

Set or get the image displayed by the button when it's selected. If you don't specify a disabled selected image, the look and feel creates one by manipulating the selected image.

 setRolloverEnabled(boolean) boolean isRolloverEnabled() void setRolloverIcon(Icon) Icon getRolloverIcon() void setRolloverSelectedIcon(Icon) Icon getRolloverSelectedIcon() 

Use setRolloverIcon(someIcon) to make the button display the specified icon when the cursor passes over it. The setRolloverSelectedIcon method lets you specify the rollover icon when the button is selectedthis is useful for two-state buttons such as toggle buttons. Setting the rollover icon automatically calls setRollover(true) , enabling rollover.

Table 4. Fine-Tuning the Button's Appearance

Method or Constructor

Purpose

 void setHorizontalAlignment(int) void setVerticalAlignment(int) int getHorizontalAlignment() int getVerticalAlignment() 

Set or get where in the button its contents should be placed. The AbstractButton class allows any one of the following values for horizontal alignment: RIGHT , LEFT , CENTER (the default), LEADING , and TRAILING . For vertical alignment: TOP , CENTER (the default), and BOTTOM .

 void setHorizontalText-         Position(int) void setVerticalText-         Position(int) int getHorizontalTextPosition() int getVerticalTextPosition() 

Set or get where the button's text should be placed, relative to the button's image. The AbstractButton class allows any one of the following values for horizontal alignment: RIGHT , LEFT , CENTER , LEADING , and TRAILING (the default). For vertical alignment: TOP , CENTER (the default), and BOTTOM .

 void setMargin(Insets) Insets getMargin() 

Set or get the number of pixels between the button's border and its contents.

 void setFocusPainted(boolean) boolean isFocusPainted() 

Set or get whether the button should look different when it has the focus.

 void setBorderPainted(boolean) boolean isBorderPainted() 

Set or get whether the border of the button should be painted .

 void setIconTextGap(int) int getIconTextGap() 

Set or get the amount of space between the text and the icon displayed in this button. Introduced in 1.4.

Table 5. Implementing the Button's Functionality

Method or Constructor

Purpose

 void setMnemonic(int) char getMnemonic() 

Set or get the keyboard alternative to clicking the button. One form of the setMnemonic method accepts a character argument; however, it's recommended that you use an int argument instead, specifying a KeyEvent.VK_X constant.

 void setDisplayedMnemonicIndex(int) int getDisplayedMnemonicIndex() 

Set or get a hint as to which character in the text should be decorated to represent the mnemonic. Not all look and feels support this. Introduced in 1.4.

 void setActionCommand(String) String getActionCommand() 

Set or get the name of the action performed by the button.

 void addActionListener(ActionListener) ActionListener removeActionListener() 

Add or remove an object that listens for action events fired by the button.

 void addItemListener(ItemListener) ItemListener removeItemListener() 

Add or remove an object that listens for item events fired by the button.

 void setSelected(boolean) boolean isSelected() 

Set or get whether the button is selected. Makes sense only for buttons that have on/off state, such as check boxes.

 void doClick() void doClick(int) 

Programmatically perform a "click." The optional argument specifies the amount of time (in milliseconds ) that the button should look pressed.

 void setMultiClickThreshhold(long) long getMultiClickThreshhold() 

Set or get the amount of time (in milliseconds) required between mouse press events for the button to generate corresponding action events. Introduced in 1.4.

Examples That Use Buttons

The following table lists some of the many examples that use buttons. Also see Examples That Use Tool Bars (page 433), which lists programs that add JButton objects to JToolBar s, Examples That Use Check Boxes (page 166), and Examples That Use Radio Buttons (page 315).

Example

Where Described

Notes

ButtonDemo

How to Use the Common Button API (page 157)

Uses mnemonics and icons. Specifies the button text position, relative to the button icon. Uses action commands.

ListDialog

How to Use JButton Features (page 159)

Implements a dialog with two buttons, one of which is the default button.

ProgressBarDemo

How to Use Progress Bars (page 300)

Implements a button's action listener with a named inner class.

 < Day Day Up > 


JFC Swing Tutorial, The. A Guide to Constructing GUIs
The JFC Swing Tutorial: A Guide to Constructing GUIs (2nd Edition)
ISBN: 0201914670
EAN: 2147483647
Year: 2004
Pages: 171

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net