Java Reference
In-Depth Information
Creating JRadioButtonMenuItem Components
The JRadioButtonMenuItem has seven constructors. They allow you to initialize the text label,
icon, and initial state.
public JCheckBoxMenuItem()
JCheckBoxMenuItem jCheckBoxMenuItem = new JCheckBoxMenuItem();
public JCheckBoxMenuItem(String text)
JCheckBoxMenuItem jCheckBoxMenuItem = new JCheckBoxMenuItem("Boy");
public JCheckBoxMenuItem(Icon icon)
Icon boyIcon = new ImageIcon("boy-r.jpg");
JCheckBoxMenuItem jCheckBoxMenuItem = new JCheckBoxMenuItem(boyIcon);
public JCheckBoxMenuItem(String text, Icon icon)
JCheckBoxMenuItem jCheckBoxMenuItem = new JCheckBoxMenuItem("Boy", boyIcon);
public JCheckBoxMenuItem(String text, boolean state)
JCheckBoxMenuItem jCheckBoxMenuItem = new JCheckBoxMenuItem("Girl", true);
public JCheckBoxMenuItem(String text, Icon icon, boolean state)
Icon girlIcon = new ImageIcon("girl-r.jpg");
JCheckBoxMenuItem jCheckBoxMenuItem = new JCheckBoxMenuItem("Girl", girlIcon, true);
public JCheckBoxMenuItem(Action action)
Action action = ...;
JCheckBoxMenuItem jCheckBoxMenuItem = new JCheckBoxMenuItem(action);
Similar to the JCheckBoxMenuItem component, the icon for the JRadioButtonMenuItem is
part of the label. This is unlike the JRadioButton , in which the icon indicates whether the radio
button is selected. If either the text label or icon isn't part of the constructor, that part of the
item label will be empty. By default, a JRadioButtonMenuItem is unselected. If you create a
JRadioButtonMenuItem that is selected and then add it to a ButtonGroup , the button group will
deselect the menu item if the group already has a selected item in the group.
Note After creating JRadioButtonMenuItem instances, remember to add them to a ButtonGroup ,
so they will work as a mutually exclusive group.
Handling JRadioButtonMenuItem Selection Events
The JRadioButtonMenuItem shares the same 18 different event/listener pairs with
JCheckBoxMenuItem . To listen for selection, attaching an ActionListener is the normal
approach. In addition, you might want to attach the same listener to all the JRadioButtonMenuItem
objects in a ButtonGroup —after all, they're in a group for a reason. If you use the same listener,
that listener can employ the current selection to perform some common operation. In other
cases, such as that in Figure 6-1, selection of any JRadioButtonMenuItem option does nothing.
 
Search WWH ::




Custom Search