Listening for Changes to the Selection in a JList Component

When the set of selected items is changed, either by the user or programmatically, a list selection event is fired.
// Create a list String[] items = {"A", "B", "C", "D"}; JList list = new JList(items); // Register a selection listener list.addListSelectionListener(new MyListSelectionListener()); class MyListSelectionListener implements ListSelectionListener { // This method is called each time the user changes the set of selected items public void valueChanged(ListSelectionEvent evt) { // When the user release the mouse button and completes the selection, // getValueIsAdjusting() becomes false if (!evt.getValueIsAdjusting()) { JList list = (JList)evt.getSource(); // Get all selected items Object[] selected = list.getSelectedValues(); // Iterate all selected items for (int i=0; i<selected.length; i++) { Object sel = selected[i]; } } } }

Comments

10 Mar 2010 - 9:46am by Anonymous (not verified)

This is by far the best no nonsense example; it works without additional components or going to getComponent(), getParent() etc.

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.