gpt4 book ai didi

java - 在 Java 中重置单选按钮

转载 作者:行者123 更新时间:2023-12-02 03:43:37 26 4
gpt4 key购买 nike

我在一个按钮组中有三个单选按钮。我希望在单击 JButton 时重置单选按钮,以便它们不被填充。我已经尝试过输入 .set 时出现的逻辑建议,但所有 boolean 值都没有执行我想要的操作。因此,如果您有任何建议,我们将不胜感激。谢谢!

最佳答案

只需使用 ButtonGroup#clearSelection

例如...

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Action;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

public static void main(String[] args) {
new Test();
}

public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}

JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public class TestPane extends JPanel {

private JRadioButton[] buttons;
private ButtonGroup buttonGroup;

public TestPane() {
buttons = new JRadioButton[] {
new JRadioButton("Nuclear"),
new JRadioButton("Gas"),
new JRadioButton("Stream"),
new JRadioButton("Peddle"),
new JRadioButton("Electric")
};
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.anchor = GridBagConstraints.WEST;
gbc.gridwidth = GridBagConstraints.REMAINDER;
buttonGroup = new ButtonGroup();
for (JRadioButton btn : buttons) {
add(btn, gbc);
buttonGroup.add(btn);
}

JButton clear = new JButton("Clear");
add(clear, gbc);

clear.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
buttonGroup.clearSelection();
}
});
}

}

}

关于java - 在 Java 中重置单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36563162/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com