日期:2014-05-20  浏览次数:20725 次

JRadioButton
如何获取group中JRadioButton的选项

group里有jrb_1和jrb_2两个单选按钮,怎么获取用户选择的结果

------解决方案--------------------
//希望能达到你的要求。做个示例给你
Java code

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);
    }
}

------解决方案--------------------
两个方法:
1 对jrb_1和jrb_2都进行监听其选择事件,实时可得是否选中状态。
比较不简洁,button多了复杂。
2 在需要知道信息的时候遍历一把,判断isSelected即可。
这个方法比较实惠,代码1楼写的比较清楚了
------解决方案--------------------
先让你的类实现ActionListener然后分别给这个两个按钮设置监听:jrb_1.addActionListener(this);
jrb_1.setActionCommand("1");
jrb_2.addActionListener(this);
jrb_2.setActionCommand("2");然后再要是现实的 
public void actionPerformed(ActionEvent a)
{
// TODO Auto-generated method stub
if(a.getActionCommand().equals("1"))
{
//你的处理
}else if(a.getActionCommand().equals("2"))
{
//你的处理
}

}