Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select item in JList using code

Tags:

java

swing

jlist

I want to be able to write a statement that manually selects an item in a JList, such as:

JList myList = new JList(items);
myList.selectValueAt(index);
like image 828
Romulus3799 Avatar asked Apr 01 '26 06:04

Romulus3799


1 Answers

Documentation of JList:

The selection state of a JList is managed by another separate model, an instance of ListSelectionModel. JList is initialized with a selection model on construction, and also contains methods to query or set this selection model. Additionally, JList provides convenient methods for easily managing the selection. These methods, such as setSelectedIndex and getSelectedValue, are cover methods that take care of the details of interacting with the selection model. By default, JList's selection model is configured to allow any combination of items to be selected at a time; selection mode MULTIPLE_INTERVAL_SELECTION. The selection mode can be changed on the selection model directly, or via JList's cover method. Responsibility for updating the selection model in response to user gestures lies with the list's ListUI.

In your case:

myList.setSelectionIndex(index);
like image 133
TMichelsen Avatar answered Apr 03 '26 19:04

TMichelsen