监听 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。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您在构造函数中
setSelectedIndex
然后,
在调用
setSelectedIndex
时添加SelectionListener
...没有监听器You
setSelectedIndex
in the constructorThen after that, add the
SelectionListener
when
setSelectedIndex
is called...there is no Listener这正是应该发生的事情。
valueChanged
仅在用户选择该项目时调用。setSelectedIndex
不会调用任何侦听器。This is exactly what should happen.
valueChanged
is only called when the user selects the item.setSelectedIndex
does not invoke any listeners.查看代码的顺序:
a) 创建列表并将索引设置为 0
b) 添加 ListSelectionListener。自从您添加侦听器以来,没有任何变化,因此没有事件被触发。
添加监听器后尝试添加:
以查看事件是否被触发。
Look at the order of you code:
a) you create the list and set the index to 0
b) you add the ListSelectionListener. Well nothing has changed since you added the listener so no event is fired.
Try adding:
after adding the listener to see if the event is fired.