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);
}}
当我用鼠标点击列表项目时,我看到消息«Selected!»。
程序启动时,此消息不显示,但选择了项目#0。
发布于 2011-02-25 23:26:48
在构造函数中使用setSelectedIndex
然后,添加SelectionListener
当setSelectedIndex为时,called...there不是监听器
发布于 2011-02-25 23:21:28
这正是应该发生的事情。仅当用户选择该项时才调用valueChanged。setSelectedIndex不会调用任何侦听器。
发布于 2011-02-25 23:26:55
看看你代码的顺序:
a)创建列表并将索引设置为0
b)添加ListSelectionListener。添加侦听器后没有发生任何变化,因此没有触发任何事件。
尝试添加:
list.setSelectedIndex(1)添加侦听器后,查看事件是否已触发。
https://stackoverflow.com/questions/5118295
复制相似问题