JRadioButton类
import javax.swing.*;import java.awt.*;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;class MyRadio{ private Jframe frame = new Jframe("一"); private Container cont = frame.getContentPane(); private JRadioButton jrb1 = new JRadioButton("1"); private JRadioButton jrb2 = new JRadioButton("2"); private JRadioButton jrb3 = new JRadioButton("3"); private JPanel pan = new JPanel(); public MyRadio(){ pan.setBorder(BorderFactory.createTitledBorder("请选择")); pan.setLayout(new GridLayout(1,3)); pan.add(this.jrb1); pan.add(this.jrb2); pan.add(this.jrb3); ButtonGroup group = new ButtonGroup(); group.add(this.jrb1); group.add(this.jrb2); group.add(this.jrb3); cont.add(pan); this.frame.setSize(330,80); this.frame.setVisible(true); this.frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { super.windowClosing(e); System.exit(1); } }); }}public class Hello { public static void main(String[] args) { new MyRadio(); }}
ButtonGroup group = new ButtonGroup();group.add(this.jrb1);group.add(this.jrb2);group.add(this.jrb3);
将按钮添加到同一个组中实现单选功能
JRadioButton事件处理使用ItemListener接口进行事件的监听
ItemEvent类
import javax.swing.*;import java.awt.*;import java.awt.event.ItemEvent;import java.awt.event.ItemListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;class MyRadio implements ItemListener{ private JLabel a = new JLabel("选中"); private JLabel b = new JLabel("未选中"); private Jframe frame = new Jframe("一"); private Container cont = frame.getContentPane(); private JRadioButton jrb1 = new JRadioButton("A",true); private JRadioButton jrb2 = new JRadioButton("B",true); private JPanel pan = new JPanel(); public MyRadio(){ ButtonGroup group = new ButtonGroup(); group.add(this.jrb1); group.add(this.jrb2); jrb1.addItemListener(this); jrb2.addItemListener(this); pan.setLayout(new GridLayout(1,4)); pan.add(this.a); pan.add(this.jrb1); pan.add(this.b); pan.add(this.jrb2); this.frame.add(pan); this.frame.setSize(200,100); this.frame.setVisible(true); this.frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { super.windowClosing(e); System.exit(1); } }); } @Override public void itemStateChanged(ItemEvent e) { if(e.getSource()==jrb2){ a.setText("未选中"); b.setText("选中"); }else { b.setText("未选中"); a.setText("选中"); } }}public class Hello { public static void main(String[] args) { new MyRadio(); }}