Ok, I'm new to listeners (still learning the language), and this is my first full-scale attempt to implement them (ie more than just a practice problem in a textbook).So far, everything is working fine except one big bug: the checkboxes don't stay checked. The ItemListener I assign them runs perfectly (I have a JOptionPane set up to trigger to let me know if it's working or not), but the box itself doesn't stay checked.I went even further and added conditional logic for if it's state is checked versus unchecked, and found that when I click the box BOTH states get triggered. So I get both JOptionPane popups, the one with the message for if the box is checked and the one for if the box isn't checked.I'm including my code here. What am I doing wrong?PS. You'll notice that the code has conditional logic to either add a radio button or a checkbox. When the program finally runs, this component is generated in multiple locations in both formats. The radio button works fine, it's the checkbox ones that I'm having the above issue with.CODE THAT CREATES THE CHECKBOXES AND ASSIGNS THE LISTENERS:public OtherField(int voteFor){ this.voteFor = voteFor; otherPanel = new JPanel(); otherPanel.setLayout(new GridLayout(1, 3)); otherField = new JTextField(10); otherField.setHorizontalAlignment(SwingConstants.CENTER); JLabel otherLabel; otherLabel = new JLabel("Other", SwingConstants.CENTER); otherRadio = new JRadioButton("", false); otherRadio.setHorizontalAlignment(SwingConstants.CENTER); otherRadio.addActionListener(new OtherFieldRadioListener()); otherCheckBox = new JCheckBox(""); otherCheckBox.setHorizontalAlignment(SwingConstants.CENTER); otherCheckBox.addItemListener(new OtherFieldCheckBoxListener()); otherPanel.add(otherLabel); otherPanel.add(otherField); if(voteFor == 1){ otherPanel.add(otherRadio); }else{ otherPanel.add(otherCheckBox); } }LISTENER CODE (it's a private class in the same class as the code above):private class OtherFieldCheckBoxListener implements ItemListener{ public void itemStateChanged(ItemEvent e){ String name = otherField.getText(); if(e.getStateChange() == ItemEvent.SELECTED){ JOptionPane.showMessageDialog(null, name); }else{ JOptionPane.showMessageDialog(null, "Not Selected"); } } } 解决方案 First thing I would try is to set the checkbox either to true or false when you initialize it, i.eotherCheckBox.setSelected(false)If this does not work I would check whether OtherField gets called from somewhere else everytime the checkbox is selected and thus the components are redrawn/ the selection is reset (use the debugger and set a breakpoint at the beginning of OtherFields) 这篇关于Java:JCheckBox 不会与 ItemListener 保持一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 09-14 23:42