user1247808 user1247808 - 4 months ago 9
Java Question

getting the selected item scrolled to top of the JList

ensureIndexIsVisible() makes the selected item appear at the end of the JList, so how do i make the selected item appear at the top of the JList instead at the end?

Answer

Try this:

  1. Get the height of each item with list.getFixedCellHeight()
  2. Get the viewport bounds with scrollpane.getViewport().getViewPosition().y
  3. Divide (2) by (1) to get the number of cells that are hidden, round it, and that's your index.

There may be an easier, built-in way. Check out the API for JList and JScrollpane.