I have a JList with some items. I’ve added a listener for when a item in the list is selected. Here is the code for what happens when an item in the list is selected:
private void questionaireNamesListValueChanged(ListSelectionEvent evt) { try { inputPanel.setEnabled(false); inputPanel.setVisible(false); inputTextField.setText(''); inputStatusLabel.setText(''); int questionaireIndex = questionaireNamesList.getSelectedIndex(); // Why will this be printed twice? System.out.println('Questionaire Index: ' + questionaireIndex); if (remoteQuestionServer.getQuestionCount(questionaireIndex) == 5) { answerQuestionButton.setEnabled(true); addQuestionButton.setEnabled(false); } else { addQuestionButton.setEnabled(true); answerQuestionButton.setEnabled(false); } } catch (RemoteException ex) { ex.printStackTrace(); } }
As you can above I put a System.out.print statement in and every time I click on something in the list I get two ouputs for that item, eg.
Questionaire Index: 4 Questionaire Index: 4 Questionaire Index: 2 Questionaire Index: 2 Questionaire Index: 0 Questionaire Index: 0 Questionaire Index: 2 Questionaire Index: 2
Any idea why this is happening?
Thanks, Patrick
When you change a selection, one or two events can occur, depending on the implementation. If index #4 is selected and you click on the second item, then the following occurs:
questionaireNamesList.getSelectedIndex()can legally return either 2 or -1.questionaireNamesList.getSelectedIndex()will surely return 2.Thus, there are two events fired. The definition of how these events are generated allows leeway for different JVM implementations do go things slightly differently.
NOTE: You should probably check the value of
ListSelectionEvent#getValueIsAdjusting()to see if the event you are processing is one in a series of events. You probably need to ignore all events where this returnstrue.