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);
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 .
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.
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....
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.
This should do it:
dataList.ensureIndexIsVisible(dataList.getSelectedIndex());
Or, if multi-selection is enabled :
dataList.scrollRectToVisible( dataList.getCellBounds( dataList.getMinSelectionIndex(), dataList.getMaxSelectionIndex() ) );
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With