单选按钮(Radio button

GUI编程中单选按钮的概念来源于电子按钮发明之前汽车无线电上的机械按钮;当你按下其
中的一个,其它被按下的按钮将被弹出。所以,单选按钮用来强制你在多个选项中只能选
择一个。


要设置一组关联的JRadioButton,你要做的就是把它们加入到一个ButtonGroup中
(窗体上可以有任意数目的按钮组)。可以设置其中的一个按钮状态为选中(true)(在构
造器的第二个参数中设置)。如果你把多个单选按钮的状态都设置为选中,那么只有最后
设置的那个有效。


下面的简单例子使用了单选按钮。注意,你可以像其它按钮那样捕获单选按钮的事件:
//: c14:RadioButtons.java
// Using JRadioButtons.
// <applet code=RadioButtons width=200 height=100></applet>
import javax.swing.*;
import java.awt.event.*; 
import java.awt.*; 
import com.bruceeckel.swing.*; 


public class RadioButtons extends JApplet { 
private JTextField t = new JTextField(15);
private ButtonGroup g = new ButtonGroup();
private JRadioButton
    rb1 = new JRadioButton("one", false),
    rb2 = new JRadioButton("two", false),
    rb3 = new JRadioButton("three", false); 
private ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent e) { 
      t.setText("Radio button " +
        ((JRadioButton)e.getSource()).getText()); 
    }
  };
public void init() { 
    rb1.addActionListener(al); 
    rb2.addActionListener(al); 
    rb3.addActionListener(al); 
    g.add(rb1); g.add(rb2); g.add(rb3); 
    t.setEditable(false); 
    Container cp = getContentPane(); 
    cp.setLayout(new FlowLayout()); 
    cp.add(t);
    cp.add(rb1);
    cp.add(rb2);
    cp.add(rb3);
  }
public static void main(String[] args) { 
    Console.run(new RadioButtons(), 200, 100); 
  }
} ///:~


这里使用了文本域来显示状态。因为它仅仅用来显示而不是收集数据,所以被设置成为不

可编辑(non-editable)。因此,这是可以用来代替Jlabel的一种选择。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值