Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java JList scroll to selected item

I have a JList with a lot of items in it, of which one is selected. I would like to scroll to the selected item in this JList, so the user can quickly see which item is selected.

How can I do this?

String[] data = {"one", "two", "three", "four", /* AND A LOT MORE */};
JList dataList = new JList(data);
JScrollPane scrollPane = new JScrollPane(dataList);
like image 315
Fortega Avatar asked Oct 09 '09 13:10

Fortega


People also ask

How do I select an item in a JList?

Add an ActionListener to the button and override the actionPerformed method. Now every time the user presses the button this method will fire up. Call getSelectedIndex to get the index of the selected item in the JList . Call getSelectedValue method to get the value of the selected item in the JList .

Is JList scrollable?

JList doesn't support scrolling directly. To create a scrolling list you make the JList the viewport view of a JScrollPane. For example: JScrollPane scrollPane = new JScrollPane(dataList); // Or in two steps: JScrollPane scrollPane = new JScrollPane(); scrollPane.

How do I select multiple items in JList?

You can access the selected indexes at any point after the selection event(s) occurs. The method JList. getSelectedIndices returns an array of currently selected indexes, and getSelectedValuesList() returns the actual items depending on what you want....

Which method of a JList returns if no item in the list is selected?

to determine which item is selected, use the getSelectedIndex() method of the JList. This returns the index of the item selected by the user, or -1 if no item is selected.


3 Answers

This should do it:

dataList.ensureIndexIsVisible(dataList.getSelectedIndex()); 
like image 94
Sbodd Avatar answered Sep 28 '22 20:09

Sbodd


Or, if multi-selection is enabled :

dataList.scrollRectToVisible(         dataList.getCellBounds(             dataList.getMinSelectionIndex(),              dataList.getMaxSelectionIndex()         ) ); 
like image 36
Nate Avatar answered Sep 28 '22 19:09

Nate


You can use the ensureIndexIsVisible method

http://java.sun.com/javase/6/docs/api/javax/swing/JList.html#ensureIndexIsVisible(int)

Scrolls the list within an enclosing viewport to make the specified cell completely visible. This calls scrollRectToVisible with the bounds of the specified cell. For this method to work, the JList must be within a JViewport.

like image 27
Sam Barnum Avatar answered Sep 28 '22 19:09

Sam Barnum