gpt4 book ai didi

Java Swing 按钮组单击时清除

转载 作者:行者123 更新时间:2023-11-30 02:42:24 24 4
gpt4 key购买 nike

我有一个按钮组,其中有 2 个单选按钮:

private javax.swing.JRadioButton jRadioButtonESPRINCIPAL;
private javax.swing.JRadioButton jRadioButtonESSECUNDARIO;
buttonGroup1 = new javax.swing.ButtonGroup();

我知道我可以通过buttonGroup1.clearSelection()清除组,但我只想在单击单选按钮时执行此操作。

我已经尝试过

    private void jRadioButtonESPRINCIPALMouseClicked(java.awt.event.MouseEvent evt) {                                                     
if (jRadioButtonESPRINCIPAL.isSelected()) {
buttonGroup1.clearSelection();
}
else{
jRadioButtonESPRINCIPAL.setSelected(true);
}
}

private void jRadioButtonESSECUNDARIOMouseClicked(java.awt.event.MouseEvent evt) {
if (jRadioButtonESSECUNDARIO.isSelected()) {
buttonGroup1.clearSelection();
}
else{
jRadioButtonESSECUNDARIO.setSelected(true);
}
}

但是没用

任何帮助将不胜感激

最佳答案

我之前的回答是错误的,抱歉。您必须像这样使用 ActionListeners:

    jRadioButtonESPRINCIPAL.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//your code goes here
}
});

然后使用一个变量来存储最后选择的RadioButton。在 ActionListener 中,您必须检查 isSelected() 是否等于最后一个选择。如果是,则使用 buttonGroup1.clearSelection();

所以最终的代码应该是这样的:

    jRadioButtonESPRINCIPAL.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (jRadioButtonESPRINCIPAL.equals(lastSelectedRadioButton)) {
buttonGroup1.clearSelection();
lastSelectedRadioButton = null;
}
else {
lastSelectedRadioButton = jRadioButtonESPRINCIPAL;
}
}
});

jRadioButtonESSECUNDARIO.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (jRadioButtonESSECUNDARIO.equals(lastSelectedRadioButton)) {
buttonGroup1.clearSelection();
lastSelectedRadioButton = null;
}
else {
lastSelectedRadioButton = jRadioButtonESSECUNDARIO;
}
}
});

关于Java Swing 按钮组单击时清除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41263947/

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