我很感兴趣,如何解释这个,这就像黑客一样?或者没有什么值得兴奋的?
也许,当您还是初学者时,您还有过其他类似的更有趣的经历吗?
警告!这不是问题(这真的很有帮助!),我只是在我的代码中寻找更多意义:)
Sooo,简而言之:最后一个 if 语句禁止一个复选框...
import javax.swing.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
class NotMain {
public static void main(String[] args) {
X x = new X();
}
}
class X implements ItemListener{
X() {
JCheckBox jCheckBox[] = new JCheckBox[2];
JPanel panel = new JPanel();
JFrame frame = new JFrame();
jCheckBox[0] = new JCheckBox("1");
jCheckBox[1] = new JCheckBox("2");
jCheckBox[0].addItemListener(this);
jCheckBox[1].addItemListener(this);
panel.add(jCheckBox[0]);
panel.add(jCheckBox[1]);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private int i;
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
i++;
} else i--;
if (i == 2) {
//if you comment next line, you'll be able to select two checkboxes
JOptionPane.showMessageDialog(null, "nope.");
}
}
}
最佳答案
当为复选框生成 mousePressed
和 mouseReleased
事件时,该复选框的状态会发生变化。这很容易证明。只需在复选框上执行 mousePressed
操作,然后将鼠标拖离复选框,然后释放鼠标即可。状态不会改变。
在您的示例中,复选框知道 mousePressed
和 mouseReleased
已完成,因此它会生成 itemStateChanged
事件,从而导致 JOptionPane被显示。
问题是 ItemStateChange
代码在 mouseReleased
代码之前执行。现在,当执行 mouseReleased
代码时,选项 Pane 具有焦点,因此复选框的状态不会更改。
将代码更改为:
if (i == 2)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
JOptionPane.showMessageDialog(null, "nope.");
}
});
}
现在,选项 Pane 的显示已添加到事件调度线程 (EDT)
的末尾,这意味着 mousePressed
和 mouseReleased
> 在显示 JOPtionPane 之前,事件由复选框处理,因此复选框的状态更改为选中。
关于java - JOptionPane.showMessageDialog - 为什么要分解复选框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51996397/