Khi hiển thị một nhóm JRadioButtons, ban đầu không có nhóm nào trong số chúng được chọn (trừ khi bạn thực thi chương trình đó). Tôi muốn có thể đặt các nút trở lại trạng thái đó ngay cả sau khi người dùng đã chọn một nút, nghĩa là không có nút nào được chọn.Bỏ chọn RadioButton trong Java Swing
Tuy nhiên, việc sử dụng các nghi phạm thông thường không mang lại hiệu quả cần thiết: gọi 'setSelected (false)' trên mỗi nút không hoạt động. Thật thú vị, nó hiện hoạt động khi các nút không được đưa vào một ButtonGroup - thật không may, sau này là cần thiết cho JRadioButtons để loại trừ lẫn nhau.
Ngoài ra, bằng cách sử dụng phương thức setSelected (ButtonModel, boolean) - của javax.swing.ButtonGroup không thực hiện những gì tôi muốn.
Tôi đã đặt cùng một chương trình nhỏ để minh họa hiệu ứng: hai nút radio và một nút JButton. Nhấp vào nút JButton sẽ bỏ chọn các nút radio để cửa sổ trông chính xác như khi nó xuất hiện lần đầu tiên.
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);
}
}
Bất kỳ ý tưởng nào? Cảm ơn!
Một ví dụ sử dụng tổ hợp phím được hiển thị [ở đây] (http://stackoverflow.com/a/37599961/230513). – trashgod