单选按钮被称为RadioButton,它通过JRadioButton类实现,例如在一些管理软件中会出现“性别”单选按钮,通过选择不同的单选按钮来实现不同性别的选择。要使用单选按钮,首先必须创建它,而后再通过其内置方法来操纵组件,所以下图将给出单选按钮的构造器。
下面将通过实例来演示如何使用单选按钮。其代码如下所示:
/**
*创建单选按钮组件,将按钮组件添加到内容面板中去
*/
publicclassBwfJRadioButton {
publicstaticintwidth=300;
publicstaticintheight=200;
publicstaticvoidmain(String args[]){
JFrame jf=newJFrame("添加单选按钮组件");
jf.setSize(width,height);
JPanel contentPane=newJPanel();
JRadioButton jr1=newJRadioButton("忽略");//创建单选按钮
JRadioButton jr2=newJRadioButton("继续");
JRadioButton jr3=newJRadioButton("跳过");
contentPane.add(jr1);//将按钮添加到内容面板中
contentPane.add(jr2);
contentPane.add(jr3);
jf.setContentPane(contentPane);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
}
}