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.
You setSelectedIndex
in the constructor
Then after that, add the SelectionListener
when setSelectedIndex
is called...there is no Listener
This is exactly what should happen. valueChanged
is only called when the user selects the item. setSelectedIndex
does not invoke any listeners.
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:
list.setSelectedIndex(1)
after adding the listener to see if the event is fired.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.