Java Swing-ButtonGroup

来源:互联网 发布:centos添加yum源 编辑:程序博客网 时间:2024/05/21 12:43

在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 ̄▽ ̄)~

原创粉丝点击