JListmyList = new JList (new String[]{"Item 1", "Item 2", "Item 3"}); myList.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { // This code is executed when the user selects an item in the list System.out.println("Selected item: " + myList.getSelectedValue()); } });
DefaultListModelThis example creates a JList using a DefaultListModel and adds three items to the list. It then adds a ListSelectionListener to the list and prints the selected item to the console when the user selects an item. These examples use the javax.swing package library.model = new DefaultListModel (); model.addElement("Item 1"); model.addElement("Item 2"); model.addElement("Item 3"); JList myList = new JList (model); myList.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { // This code is executed when the user selects an item in the list System.out.println("Selected item: " + myList.getSelectedValue()); } });