单选按钮(Radio button

本文介绍了在GUI编程中如何使用JRadioButton创建单选按钮,并通过将按钮添加到ButtonGroup来确保用户只能选择一个选项。通过示例代码演示了如何设置按钮状态和响应事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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的一种选择。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值