为什么JList选择发生两次? [英] Why do JList selections occur twice?

查看:79
本文介绍了为什么JList选择发生两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含某些项目的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();
    }
} 

如上所述,我在其中输入了System.out.print语句,每次单击列表中的某项,都会得到该项目的两个输出,例如.

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

知道为什么会这样吗?

谢谢, 帕特里克

推荐答案

更改选择时,根据实现的不同,可能会发生一个或两个事件.如果选择索引#4,然后单击第二项,则会发生以下情况:

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:

  • 首先,索引#4被取消选择.根据型号,questionaireNamesList.getSelectedIndex()可以合法地返回2或-1.
  • 秒,选择索引#2.此时,questionaireNamesList.getSelectedIndex()肯定会返回2.
  • 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.

因此,有两个事件被触发.有关如何生成这些事件的定义,为不同的JVM实现留出了余地,但情况确实有所不同.

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.

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

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.

这篇关于为什么JList选择发生两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆