Java Reference
In-Depth Information
The ToggleButtonModel class defines the default data model for both the JToggleButton
and its subclasses JCheckBox and JRadioButton , described in this chapter, as well as the
JCheckBoxMenuItem and JRadioButtonMenuItem classes described in Chapter 6.
Note Internally, Swing's HTML viewer component uses the ToggleButtonModel for its check box and
radio button input form elements.
ButtonGroup Class
Before describing the ButtonGroup class, let's demonstrate its usage. The program shown in
Listing 5-1 creates objects that use the ToggleButtonModel and places them into a single group.
As the program demonstrates, in addition to adding the components into the screen's container,
you must add each component to the same ButtonGroup . This results in a pair of add() method
calls for each component. Furthermore, the container for the button group tends to place
components in a single column and to label the grouping for the user with a titled border,
though neither of these treatments are required. Figure 5-1 shows the output of the program.
Listing 5-1. Odd Collection of Button Components
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
public class AButtonGroup {
public static void main(String args[]) {
Runnable runner = new Runnable() {
public void run() {
JFrame frame = new JFrame("Button Group");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(0, 1));
Border border =
BorderFactory.createTitledBorder("Examples");
panel.setBorder(border);
ButtonGroup group = new ButtonGroup();
AbstractButton abstract1 =
new JToggleButton("Toggle Button");
panel.add(abstract1);
group.add(abstract1);
AbstractButton abstract2 =
new JRadioButton("Radio Button");
panel.add(abstract2);
group.add(abstract2);
 
Search WWH ::




Custom Search