【问题标题】:method getSelectionIndex() in ListSelectionListenerListSelectionListener 中的方法 getSelectionIndex()
【发布时间】:2013-04-16 11:56:13
【问题描述】:

例如,我有一个名为 cross_list 的 JList,其中包含一个项目列表,现在我向该 JList 添加一个 ListSelectionListener

考虑这些代码行:

class AcrossListHandler implements ListSelectionListener {
    @Override
    public void valueChanged(ListSelectionEvent e) {
        JList lsm = (JList) e.getSource();
        int selected_index = lsm.getMaxSelectionIndex();            
            if (selected_index >= 0){
                System.out.println(selected_index);
            }
        }  
     }       
}

我有一个问题:为什么“System.out.println()”行打印 2 个 selected_value 值,而我只在 JList 中的索引上单击 1 次???

【问题讨论】:

    标签: java swing jlist


    【解决方案1】:

    由 ui-delegate 注册的 listSelectionListener 将选择更改标记为在 mousePressed 上进行中,并在 mouseReleased 中重置该标志,使其成为最终状态。如果您只想对最终确定的更改做出反应,您可以查询 valueIsAdjusting 属性,如果为 true,则不执行任何操作:

    class AcrossListHandler implements ListSelectionListener {
    
        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (e.getValueIsAdjusting()) return;
            // do stuff
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-02-14
      • 2012-07-09
      • 2013-09-25
      • 2015-05-12
      • 2020-10-02
      • 2011-04-18
      • 2015-07-19
      • 2012-10-10
      • 1970-01-01
      相关资源
      最近更新 更多