简体   繁体   中英

How to add an action Listener in DefaultListModel and not in JList

I have the following code and i add elements to a JList .

DefaultListModel listModel = new DefaultListModel();
listModel.addElement("element1");
listModel.addElement("element2");
listModel.addElement("element3");
list = new JList(listModel);
list.addListSelectionListener(this);

In another method of my code

  • I remove all the elements of listModel( DefaultListModel ) and
  • I add the elements of a SortedSet : ( listModel is a public static variable)

     listModel.removeAllElements(); SortedSet<String> keys = new TreeSet<String>(myHashMap.keySet()); Iterator<String> it = keys.iterator(); while (it.hasNext()) { String key = it.next(); listModel.addElement(key); //How can i add an addActionListener to every 'key element' //since the JList list variable is not global ?? } 

Since 'list' is not a public static variable, how can I add an Action Listener to each one of the list Items in the listModel?

I tried to use an addListDataListener , but I don't think that is use for the purpose that I need.

This is what you need:

List selection events occur when the selection in a list or table is either changing or has just changed. List selection events are fired from an object that implements the ListSelectionModel interface. To get a table's list selection model object, you can use either getSelectionModel method or getColumnModel().getSelectionModel().

http://docs.oracle.com/javase/tutorial/uiswing/events/listselectionlistener.html

Maybe you can use the concepts presented in List Action . It will execute an Acton on an item in the JList when you double click on the item or use the Enter key on the selected item.

Or if you just want to know when an item is selected by a single mouse click or by using the up/down arrow keys then you should be using a ListSelectionListener . See How to Write a ListSelectionListener .

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.

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