Patrick Kiernan
Patrick Kiernan

Reputation: 259

Why do JList selections occur twice?

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

Upvotes: 7

Views: 3122

Answers (2)

Eddie
Eddie

Reputation: 54421

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:

  • First, index #4 is UNSELECTED. Depending on the model, questionaireNamesList.getSelectedIndex() can legally return either 2 or -1.
  • second, index #2 is SELECTED. At this point, 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 returns true.

Upvotes: 13

TofuBeer
TofuBeer

Reputation: 61536

Further to the answer by Eddie look at the getValueIsAdjusting method on the event.

Upvotes: 2

Related Questions