JList:addListSelectionListener(ListSelectionListener l)
To determine if elements in a JList have been selected,you have to add JList:addListSelectionListener
Previous post we added ActionListener to JList
Below Code sets Application look and feel to WindowsClassicLookAndFeel
[
Previous post we added ActionListener to JList
JList:addListSelectionListener Example
[
import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JScrollPane; import javax.swing.UIManager; import java.util.ArrayList; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.JLabel; import javax.swing.JButton; public class JListExample extends JFrame implements ListSelectionListener{ public JList<String> list; public JLabel label; JListExample() { super("JFrame Example"); try { UIManager.setLookAndFeel
("com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel"); } catch(Exception e) { } ArrayList arr=new ArrayList(); arr.add("Java"); arr.add("C#"); arr.add("C++"); list=new JList(arr.toArray()); list.setBounds(50, 50, 100, 100); add(list); list.addListSelectionListener(this); setSize(400,400); setLayout(null); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); setVisible(true); } public void valueChanged(ListSelectionEvent event) { if(event.getValueIsAdjusting()) return; System.out.println("Value changed from " +event.getLastIndex() +
" to " +event.getFirstIndex()); } public static void main(String args[]) { new JListExample(); } }
]
JList:addListSelectionListener Output
Below Code sets Application look and feel to WindowsClassicLookAndFeel
[
try { UIManager.setLookAndFeel
("com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel"); } catch(Exception e) {]
setDefaultCloseOperation(EXIT_ON_CLOSE) ensures the application exits when the
close button is clicked