java radio 不可选_在Java Swing中取消选择RadioButtons

当显示一组JRadioButton时,最初没有选择任何一个(除非您以编程方式强制执行)。我想要能够将按钮恢复到该状态,即使在用户已经选择了一个之后,即,不应该选择任何按钮。

然而,使用通常的嫌疑不会提供所需的效果:调用’setSelected(false)’在每个按钮不工作。有趣的是,当按钮未放入ButtonGroup时,它会工作 – 不幸的是,后者是JRadioButtons要求是互斥的。

此外,使用javax.swing.ButtonGroup的setSelected(ButtonModel,boolean)方法不会做我想要的。

我把一个小程序来展示效果:两个单选按钮和一个JButton。单击JButton应取消选择单选按钮,以使窗口看起来与它首次弹出时的完全一样。

import java.awt.Container;

import java.awt.GridLayout;

import java.awt.event.*;

import javax.swing.*;

/**

* This class creates two radio buttons and a JButton. Initially, none

* of the radio buttons is selected. Clicking on the JButton should

* always return the radio buttons into that initial state, i.e.,

* should disable both radio buttons.

*/

public class RadioTest implements ActionListener {

/* create two radio buttons and a group */

private JRadioButton button1 = new JRadioButton("button1");

private JRadioButton button2 = new JRadioButton("button2");

private ButtonGroup group = new ButtonGroup();

/* clicking this button should unselect both button1 and button2 */

private JButton unselectRadio = new JButton("Unselect radio buttons.");

/* In the constructor, set up the group and event listening */

public RadioTest() {

/* put the radio buttons in a group so they become mutually

* exclusive -- without this, unselecting actually works! */

group.add(button1);

group.add(button2);

/* listen to clicks on 'unselectRadio' button */

unselectRadio.addActionListener(this);

}

/* called when 'unselectRadio' is clicked */

public void actionPerformed(ActionEvent e) {

/* variant1: disable both buttons directly.

* ...doesn't work */

button1.setSelected(false);

button2.setSelected(false);

/* variant2: disable the selection via the button group.

* ...doesn't work either */

group.setSelected(group.getSelection(), false);

}

/* Test: create a JFrame which displays the two radio buttons and

* the unselect-button */

public static void main(String[] args) {

JFrame frame = new JFrame();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

RadioTest test = new RadioTest();

Container contentPane = frame.getContentPane();

contentPane.setLayout(new GridLayout(3,1));

contentPane.add(test.button1);

contentPane.add(test.button2);

contentPane.add(test.unselectRadio);

frame.setSize(400, 400);

frame.setVisible(true);

}

}

任何想法任何人?谢谢!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值