1

I have a JPanel in a JScrollPane, and the JPanel contains many small JPanels. But the default position of scrollbar is not at the top, thus the small JPanels isn't shown from the first one. How to let scrollbar's default position be at top?

My code is simplified and looks like this:

JFrame resultFrame = new JFrame("Searching Result");

JPanel listPanel = new JPanel();
listPanel.setLayout(new BoxLayout(listPanel, BoxLayout.Y_AXIS));
for (int i=0; i<5; i++) {
    listPanel.add(smallPanel) // smallPanel is created in another class, which is related to i.
}
JScrollPane scrollPanel = new JScrollPane(listPanel);
scrollPanel.setPreferredSize(new Dimension(500, 750));

resultFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
resultFrame.setContentPane(scrollPanel);
resultFrame.pack();
resultFrame.setLocationRelativeTo(null);
resultFrame.setVisible(true);
gaofangshu
  • 41
  • 1
  • 6
  • 1
    Have you tried `scrollPanel.getVerticalScrollBar().setValue(0);` [This](http://stackoverflow.com/questions/2544758/how-to-adjust-position-of-scroll-in-the-scrollpane) is a related thread. – Stefan Lindner Feb 01 '17 at 07:50
  • After playing around with your example, the `JScrollPane` offset starts at `0x0` for me just fine – MadProgrammer Feb 01 '17 at 07:50
  • @StefanLindner, Yes, but it didn't work :( – gaofangshu Feb 01 '17 at 07:55
  • Did you check this http://stackoverflow.com/questions/1166072/setting-scroll-bar-on-a-jscrollpane ? – Subala Feb 01 '17 at 08:02
  • @Subala Thank you! I check this again. `javax.swing.SwingUtilities.invokeLater(...)` works, meanwhile, just `scrollPanel.getVerticalScrollBar().setValue(0)` doesn't work. Do you know why? – gaofangshu Feb 01 '17 at 08:11
  • @GAOFangshu This has been answered [here](http://stackoverflow.com/questions/3551542/swingutilities-invokelater-why-is-it-needed) – Subala Feb 02 '17 at 06:21

0 Answers0