[英]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);
}
} }
When I click on list item with mouse, I see message «Selected!». 当我用鼠标点击列表项时,我看到消息«选择!»。
When program start, this message not shown, but item #0 is selected. 程序启动时,此消息未显示,但选择了项目#0。
You setSelectedIndex
in the constructor 你在构造函数中
setSelectedIndex
Then after that, add the SelectionListener
然后,添加
SelectionListener
when setSelectedIndex
is called...there is no Listener 当
setSelectedIndex
时......没有监听器
This is exactly what should happen. 这正是应该发生的事情。
valueChanged
is only called when the user selects the item. valueChanged
仅在用户选择项目时调用。 setSelectedIndex
does not invoke any listeners. setSelectedIndex
不会调用任何侦听器。
Look at the order of you code: 看看你的代码顺序:
a) you create the list and set the index to 0 a)创建列表并将索引设置为0
b) you add the ListSelectionListener. b)添加ListSelectionListener。 Well nothing has changed since you added the listener so no event is fired.
自从您添加了侦听器以来没有任何更改,因此没有触发任何事件。
Try adding: 尝试添加:
list.setSelectedIndex(1)
after adding the listener to see if the event is fired. 添加侦听器后查看是否触发了事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.