为什么我的程序在 ItemStateChanged
事件中调用 showMessageDialog
两次,即使我把它放在 if else 中?
private void checkBox1ItemStateChanged(java.awt.event.ItemEvent evt) {
if(evt.getStateChange() == ItemEvent.SELECTED){
//System.out.println("Check box 1 selected");
JOptionPane.showMessageDialog(null, "Check box 1 selected");
}
else{
//System.out.println("Check box 1 deselected");
JOptionPane.showMessageDialog(null, "Check box 1 deselected");
}
}
如果我只使用System.out.println
,程序将正确运行。
最佳答案
在显示 JOptionPane 之前,复选框的状态不会更新。 (请注意,当显示第一个选项 Pane 时,复选标记是如何不绘制的。
因此,您需要做的是通过使用 SwingUtilities.invokeLater(...) 显示 JOptionPane,确保在显示 JOption Pane 之前更新并重新绘制状态:
checkBox.addItemListener( new ItemListener()
{
public void itemStateChanged(java.awt.event.ItemEvent evt)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
if(evt.getStateChange() == ItemEvent.SELECTED)
{
JOptionPane.showMessageDialog(null, "Check box 1 selected");
}
else
{
JOptionPane.showMessageDialog(null, "Check box 1 deselected");
}
}
});
}
});
关于java - JCheckBox:在 ItemStateChanged 事件中两次显示 MessageDialog,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40308135/