Web site developers - 662 Graphical User Interface Components: Part 1 Chapter
662 Graphical User Interface Components: Part 1 Chapter 12 12.6 JButton A button is a component the user clicks to trigger a specific action. A Java program can use several types of buttons, including command buttons, check boxes, toggle buttons and radio buttons. Figure 12.9 shows the inheritance hierarchy of the Swing buttons we cover in this chapter. As you can see in the diagram, all the button types are subclasses of Abstract- Button(package javax.swing), which defines many of the features that are common to Swing buttons. In this section, we concentrate on buttons that are typically used to initiate a command. Other button types are covered in the next several sections. A command button generates an ActionEventwhen the user clicks the button with the mouse. Command buttons are created with class JButton, which inherits from class AbstractButton. The text on the face of a JButtonis called a button label. A GUI can have many JButtons, but each button label typically should be unique. Look-and-Feel Observation 12.4 Having more than one JButtonwith the same label makes the JButtons ambiguous to the user. Be sure to provide a unique label for each button. The application of Fig. 12.10 creates two JButtons and demonstrates that JButtons (like JLabels) support the display of Icons. Event handling for the buttons is performed by a single instance of inner class ButtonHandler(defined at lines 53 62). javax.swing.JComponent javax.swing.AbstractButton javax.swing.JButton javax.swing.ToggleButton javax.swing.JCheckBox javax.swing.JRadioButton Fig. 12.9The button hierarchy. 12. 1 // Fig. 12.10: ButtonTest.java 2 // Creating JButtons. 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*; 10 11 public class ButtonTest extends JFrame { 12 private JButton plainButton, fancyButton; Fig. 12.10 Fig. 12.10 Demonstrating command buttons and action events (part 1 of 3). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01