Mega Code Archive

 
Categories / Java Tutorial / Swing
 

To programmatically move the list to the top

The firstVisibleIndex and lastVisibleIndex properties allow you to find out which choices are currently visible. To request that a specific element be made visible, use the public void ensureIndexIsVisible(int index) method. import java.awt.BorderLayout; import javax.swing.DefaultListModel; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JScrollPane; public class SizingSamples {   public static void main(String args[]) {     JFrame frame = new JFrame("Sizing Samples");     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     DefaultListModel model = new DefaultListModel();     model.ensureCapacity(100);     for (int i = 0; i < 100; i++) {         model.addElement(Integer.toString(i));     }     JList jlist2 = new JList(model);          JScrollPane scrollPane2 = new JScrollPane(jlist2);     frame.add(scrollPane2, BorderLayout.CENTER);     frame.setSize(300, 350);     frame.setVisible(true);          jlist2.ensureIndexIsVisible(50);   } }