import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class HK extends JFrame { JPanel jp=null; JRadioButton[] jb; JButton jt=new JButton("Submit"); public HK() { jp=(JPanel)this.getContentPane(); jp.setLayout(null); jb=new JRadioButton[3]; for(int i=0;i<3;i++) { jb[i]=new JRadioButton("jb"+(i+1)); } for(int i=0;i<3;i++) { jb[i].setBounds(new Rectangle(20+60*i,20,60,25)); jp.add(jb[i]); } jt.setBounds(new Rectangle(20,60,75,25)); jp.add(jt); jt.addActionListener(new HK_bt_actionAdapter(this)); } public static void main(String[] args) { HK frame=new HK(); frame.setSize(400,200); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void bt_actionPerformed(ActionEvent e) { for(int i=0;i<3;i++) { if(jb[i].isSelected())//判断是否选中,true为选中,false为没选中. { System.out.println(jb[i].getText());//输出选中的 } } } } class HK_bt_actionAdapter implements ActionListener { private HK adaptee; HK_bt_actionAdapter(HK adaptee) { this.adaptee = adaptee; } public void actionPerformed(ActionEvent e) { adaptee.bt_actionPerformed(e); } }
//PS:今天在论坛上看到一个同仁不会用JRadioButton,特地做了一个示例作为参考。