JRadioButton,ActionListener Example
This JRadioButton example creates four radio buttons and attaches a listener to them. Radio buttons enable a user to select from a number of choices.
The buttons are added to a ButtonGroup to enable other buttons in the group to be de-selected when one is selected.
Run the program, and select different radio buttons in turn to see what happens.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// JRadioButton ActionListener Example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class JRadioButtonExample2 {
public static void main(String[] args) {
JFrame frame = new JFrame();
Container cp = frame.getContentPane();
cp.setLayout(new FlowLayout());
ActionListener listener = new ActionListener() {
public void actionPerformed (ActionEvent e) {
System.out.println(e.getActionCommand());
};
};
ButtonGroup group = new ButtonGroup();
String[] sa = {"pink","magenta","orange","cyan"};
for(int i=0;i<sa.length;++i) {
JRadioButton b = new JRadioButton(sa[i]);
group.add(b);
cp.add(b);
b.addActionListener(listener);
}
frame.setSize(300,60);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
11-12 For convenience we assign the frame's content pane to a variable.
The method setLayout() assigns a layout manager to the content pane.
A layout manager, as discussed later, organizes the layout of components on the content pane.
14-18 The action listener is constructed similarly to the one on the 'Action Listener (a)' page.
The ActionEvent parameter of actionPerformed() enables relevant information about the event to be determined.
Its getSource() method can be used to yield the component generating the event. Here its getActionCommand() method returns the string label of the radio button selected.
20-21 A ButtonGroup is constructed.
An array of strings is constructed. The strings are used as textual labels for the radio buttons.
23-28 Each iteration of the loop:
- constructs a radio button
- adds it to the group
- adds it to the content pane
- adds the listener to it.
