In Java, you can get the selected item or items from a JList using the getSelectedValue() and getSelectedValuesList() methods respectively. Here are the steps to get the selected item(s) from a JList:
-
Get the reference to the JList instance:
JList<String> myList = new JList<>(items);
-
Get the selected item(s) using one of the following methods:
-
getSelectedValue(): Returns the first selected item as an object. If no item is selected, returns null.
String selectedValue = myList.getSelectedValue();
-
getSelectedValuesList(): Returns a list of all the selected items as a List object. If no item is selected, returns an empty list.
List<String> selectedValuesList = myList.getSelectedValuesList();
Note: The getSelectedValue() method returns only the first selected item even if the JList is set to multiple selection mode. To get all the selected items, use the getSelectedValuesList() method.
Once you have obtained the selected item(s), you can perform various operations on them, such as displaying them in a message box, passing them to a function, or updating the UI based on the selected items.