The fontList ( jList ) list containing font names is jScrollPane. The default is fontList.setSelectedIndex(20) . Tell scrollPane how to make scrollPane initially scroll to the default selected (index 20) value in the list?

    2 answers 2

    Try this:

     fontList.setSelectedIndex(10); // селектим элемент ... int size = fontList.getModel().getSize(); // получаем количество элементов int scrollmax = scrollPane.getVerticalScrollBar().getMaximum(); // получаем размер скролла int selected = fontList.getSelectedIndex(); scrollPane.getVerticalScrollBar() .setValue(scrollmax / size * selected); // ставим скролл на нужную позицию 

    Example


    enter image description here

    • It worked perfectly! Just what was needed! Thank you very much! - Tim Leyden

    For JList you can use this code:

     list.ensureIndexIsVisible( list.getSelectedIndex() ); 

    For swing components, there is a JComponent.scrollRectToVisible :

     int selected = list.getSelectedIndex(); if ( selected != -1 ) { // getCellBounds возвращает null для значений вне списка list.scrollRectToVisible( list.getCellBounds( selected, selected ) ); } 

    The code JScrollPane parent JScrollPane to make the first selected row visible (the line will be at the bottom of the scroll pane).