7

我有一个包含一些项目的 JList。我添加了一个侦听器,以便选择列表中的项目。以下是选择列表中的项目时发生的情况的代码:

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();
    }
} 

正如您在上面可以看到的那样,我在其中添加了一条System.out.print语句,每次单击列表中的某些内容时,我都会得到该项目的两个输出,例如。

Questionaire Index: 4
Questionaire Index: 4
Questionaire Index: 2
Questionaire Index: 2
Questionaire Index: 0
Questionaire Index: 0
Questionaire Index: 2
Questionaire Index: 2

知道为什么会这样吗?

谢谢,帕特里克

4

2 回答 2

13

当您更改选择时,可能会发生一两个事件,具体取决于实现。如果选择索引 #4 并单击第二项,则会发生以下情况:

  • 首先,索引#4 未选择。根据型号,questionaireNamesList.getSelectedIndex()可以合法地返回 2 或 -1。
  • 其次,索引#2 被选中。此时,questionaireNamesList.getSelectedIndex()肯定会返回2。

因此,触发了两个事件。这些事件如何生成的定义为不同的 JVM 实现留有余地,它们的处理方式略有不同。

注意:您可能应该检查 的值ListSelectionEvent#getValueIsAdjusting()以查看您正在处理的事件是否是一系列事件中的一个。您可能需要忽略 this 返回的所有事件true

于 2009-03-14T17:24:14.777 回答
2

除了 Eddie 的回答,请查看事件的 getValueIsAdjusting 方法。

于 2009-03-14T17:33:28.060 回答