java radio 不可选_在Java Swing中取消选择RadioButtons
當顯示一組JRadioButton時,最初沒有選擇任何一個(除非您以編程方式強制執(zhí)行)。我想要能夠?qū)粹o恢復到該狀態(tài),即使在用戶已經(jīng)選擇了一個之后,即,不應(yīng)該選擇任何按鈕。
然而,使用通常的嫌疑不會提供所需的效果:調(diào)用’setSelected(false)’在每個按鈕不工作。有趣的是,當按鈕未放入ButtonGroup時,它會工作 – 不幸的是,后者是JRadioButtons要求是互斥的。
此外,使用javax.swing.ButtonGroup的setSelected(ButtonModel,boolean)方法不會做我想要的。
我把一個小程序來展示效果:兩個單選按鈕和一個JButton。單擊JButton應(yīng)取消選擇單選按鈕,以使窗口看起來與它首次彈出時的完全一樣。
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);
}
}
任何想法任何人?謝謝!
總結(jié)
以上是生活随笔為你收集整理的java radio 不可选_在Java Swing中取消选择RadioButtons的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql 闪回_MySQL数据误删除的
- 下一篇: 引用和指针的区别都有什么_C++指针与引