Java Swing-ButtonGroup

在Java Swing中,RadioButton是一个很常用的组件,在使用RadioButton时候,如何知道一组RadioButton是属于一组的呢?只有在同一个按钮组中,多个RadioButton才是互斥的,因此,RadioButton类常常搭配ButtonGroup类一同使用,经常会搭配ButtonGroup使用,例如:

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JTextField;


public class ButtonGroupText extends JFrame implements ActionListener {
   public JRadioButton JrbtnMale,JrbtnFemale;
   public ButtonGroup Bg;
   public JTextField JtfShow;

  public ButtonGroupText() {
    // TODO Auto-generated constructor stub
      super("ButtonGroup的使用");
      this.setBounds(400, 400, 400, 200);
      this.setBackground(Color.lightGray);
      this.setLayout(new FlowLayout());

      JrbtnMale=new JRadioButton("男");
      JrbtnFemale=new JRadioButton("女");          //JRadioButton的对象实例化
      Bg=new ButtonGroup();                                  //这里注意,ButtonGroup并不是组件,所以不用add进Frame中
      Bg.add(JrbtnFemale);                                       //为ButtonGroup添加进一组JRadioButton
      Bg.add(JrbtnMale);
      this.add(JrbtnFemale);                                    
      this.add(JrbtnMale);
      JrbtnFemale.addActionListener(this);           //注册时间监听器事件
      JrbtnMale.addActionListener(this);

      this.add(JtfShow=new JTextField(10));
      this.setVisible(true);
}
    @Override
    public void actionPerformed(ActionEvent arg0) {
        // TODO Auto-generated method stub
        if(arg0.getActionCommand().equals("男")){                               //接收动作并显示在文本框中
            JtfShow.setText("选择了“男");
        }
        else {
            JtfShow.setText("选择了”女");
        }
    }


    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ButtonGroupText example=new ButtonGroupText();
    }
}

完成的效果如下:
这里写图片描述

这里要注意一点,ButtonGroup并不是组件,所以不用使用add方法添加进窗体中,如何判断选择了哪一个RadioButton,在这里使用的是GetActionCommand(),获取动作发生组件的内容来比较,本来觉得应该用更简单的方法获取,但是Java中ButtonGroup并没有提供直接获取选中值的方法,ButtonGroup的全部方法如下:

void add(AbstractButton b)———–将按钮添加到组中。
void clearSelection()————清除选中内容,从而没有选择 ButtonGroup 中的任何按钮。
int getButtonCount()———返回此组中的按钮数。
Enumeration getElements()———返回此组中的所有按钮。
ButtonModel getSelection()———返回选择按钮的模型。
boolean isSelected(ButtonModel m)———返回对是否已选择一个 ButtonModel 的判断。
void remove(AbstractButton b)——–从组中移除按钮。
void setSelected(ButtonModel m, boolean b)——为 ButtonModel 设置选择值。

所以只好使用if-else进行逐个的判断了,不过好在一般使用RadioButton的选项并不多,如果找到了更好的方法再更新~(~o ̄▽ ̄)~

  • 12
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值