JRadioButton

mei1203 2012-08-01 01:03:37
如何获取group中JRadioButton的选项

group里有jrb_1和jrb_2两个单选按钮,怎么获取用户选择的结果
...全文
99 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
q6823221 2012-08-01
  • 打赏
  • 举报
回复
先让你的类实现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"))
{
//你的处理
}

}
xu200074212 2012-08-01
  • 打赏
  • 举报
回复
两个方法:
1 对jrb_1和jrb_2都进行监听其选择事件,实时可得是否选中状态。
比较不简洁,button多了复杂。
2 在需要知道信息的时候遍历一把,判断isSelected即可。
这个方法比较实惠,代码1楼写的比较清楚了
shenhua 2012-08-01
  • 打赏
  • 举报
回复
//希望能达到你的要求。做个示例给你

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

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧