繁体   English   中英

侦听JList setSelectedIndex

[英]Listen JList setSelectedIndex

MyJList myList = new MyJList();
    myList.addListSelectionListener(new ListSelectionListener() {

    @Override
    public void valueChanged(ListSelectionEvent e) {

    if(!e.getValueIsAdjusting()){
        System.out.println("Selected!");
    }
    }
});

class MyList extends JList{


    public MyList () {
    super();

    this.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 

    this.setSelectedIndex(0);

   }

}

当我用鼠标点击列表项时,我看到消息«选择!»。

程序启动时,此消息未显示,但选择了项目#0。

你在构造函数中setSelectedIndex

然后,添加SelectionListener

setSelectedIndex时......没有监听器

这正是应该发生的事情。 valueChanged仅在用户选择项目时调用。 setSelectedIndex不会调用任何侦听器。

看看你的代码顺序:

a)创建列表并将索引设置为0
b)添加ListSelectionListener。 自从您添加了侦听器以来没有任何更改,因此没有触发任何事件。

尝试添加:

list.setSelectedIndex(1)

添加侦听器后查看是否触发了事件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM