that you will normally implement the ActionListener interface. Recall that the only method
defined by ActionListener is actionPerformed( ). Inside this method, you can use a number
of different ways to determine which button was selected. First, you can check its action
command by calling getActionCommand( ). By default, the action command is the same
as the button label, but you can set the action command to something else by calling
setActionCommand( ) on the radio button. Second, you can call getSource( ) on the
ActionEvent object and check that reference against the buttons. Finally, you can simply
check each radio button to find out which one is currently selected by calling isSelected( )
on each button. Remember, each time an action event occurs, it means that the button being
selected has changed and that one and only one button will be selected.
The following example illustrates how to use radio buttons. Three radio buttons are
created. The buttons are then added to a button group. As explained, this is necessary to cause
their mutually exclusive behavior. Pressing a radio button generates an action event, which is
handled by actionPerformed( ). Within that handler, the getActionCommand( ) method gets
the text that is associated with the radio button and uses it to set the text within a label.
// Demonstrate JRadioButton
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JRadioButtonDemo" width=300 height=50>
</applet>
*/
public class JRadioButtonDemo extends JApplet
implements ActionListener {
JLabel jlab;
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Create radio buttons and add them to content pane.
JRadioButton b1 = new JRadioButton("A");
b1.addActionListener(this);
add(b1);
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home