Hi all I am having some difficulties with adding a joptionpane in JcheckBox listener
public void itemStateChanged(ItemEvent evt) {
if(evt.getStateChange() == ItemEvent.SELECTED){
///some code
JOptionPane.showMessageDialog(null, "Message", "Alert",
JOptionPane.INFORMATION_MESSAGE);
}
}
so it works fine,but the problem is that the JCheckBox gets selected and immediately deselected how can I manage to fix this ?
Che开发者_如何学Pythoners
There are a couple of suggestions here (solution) to use an action listener instead of a item listener. This does work, however, I though it strange given that all the texts I have suggest an item listener is the expected type of listener for a check box.
In fact, this is a known bug as acknowledged by Oracle Bug ID:6924233 The JOptionPane apparently causes another event to be generated.
The recommended fix is to invoke the JOptionPane using invokeLater. This works fine and involves only a minor code change to a program already using an item listener for other purposes.
The problem must be in "///some code" as the following test program works for me in Java 6:
public class CheckBoxItemListener {
public static void main(String[] args) {
final JCheckBox checkBox = new JCheckBox("Click me");
JFrame frame = new JFrame("CheckBox Item Listener");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(100, 100, 300, 300);
frame.add(checkBox);
frame.setVisible(true);
checkBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent evt) {
if (evt.getStateChange() == ItemEvent.SELECTED){
JOptionPane.showMessageDialog(null, "Message", "Alert",
JOptionPane.INFORMATION_MESSAGE);
}
}
});
}
}
Have a look in the omitted code for setSelected or doClick calls.
精彩评论