代码如下 import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RadioButtonDemo extends JFrame implements ActionListener{
private JLabel Label;
private ButtonGroup bGroup;
private JRadioButton rButton;
public RadioButtonDemo(){
setTitle("JRadionButtonDemo");
setSize(250,100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new FlowLayout());
Label = new JLabel("单击下面按钮将触发动作事件");
getContentPane().add(Label);
bGroup = new ButtonGroup();
rButton = new JRadioButton("JRadionButton1",true);
rButton.addActionListener(this);
bGroup.add(rButton);
rButton.setActionCommand("JRadioButton1");
getContentPane().add(rButton);
rButton = new JRadioButton("JRadioButton2",false);
rButton.addActionListener(this);
bGroup.add(rButton);
rButton.setActionCommand("JRadioButton2");
getContentPane().add(rButton);
}
public void actionPerformed(ActionEvent e){
String command =bGroup.getSelection().getActionCommand();
if(command.equals("JRadioButton1")){
Label.setText("您选择了JRadioButton1单选按钮");
}
if(command.equals("JRadioButton2")){
Label.setText("您选择了JRadioButton2单选按钮");
}
}
public static void main(String[] args){
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new RadioButtonDemo();
Frame.show();
}
}