Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do JList selections occur twice?

Tags:

java

swing

jlist

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

like image 291
Patrick Kiernan Avatar asked Mar 14 '09 17:03

Patrick Kiernan


2 Answers

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.

like image 89
Eddie Avatar answered Sep 22 '22 12:09

Eddie


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

like image 29
TofuBeer Avatar answered Sep 19 '22 12:09

TofuBeer