Java 如何让滚动条';谁的默认位置在顶部?

Java 如何让滚动条';谁的默认位置在顶部?,java,swing,jscrollpane,Java,Swing,Jscrollpane,我在JScrollPane中有一个JPanel,JPanel包含许多小JPanel。但是滚动条的默认位置不在顶部,因此小的JPanel不会从第一个屏幕开始显示。如何让滚动条的默认位置位于顶部 我的代码经过简化,如下所示: JFrame resultFrame = new JFrame("Searching Result"); JPanel listPanel = new JPanel(); listPanel.setLayout(new BoxLayout(listPanel, BoxLayo

我在JScrollPane中有一个JPanel,JPanel包含许多小JPanel。但是滚动条的默认位置不在顶部,因此小的JPanel不会从第一个屏幕开始显示。如何让滚动条的默认位置位于顶部

我的代码经过简化,如下所示:

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);
JFrame resultFrame=newjframe(“搜索结果”);
JPanel listPanel=newjpanel();
setLayout(新的BoxLayout(listPanel,BoxLayout.Y_轴));

对于(int i=0;我已经尝试了
scrollPanel.getVerticalScrollBar().setValue(0);
是一个相关的线程。在仔细研究了您的示例之后,
JScrollPane
偏移量从
0x0
开始fine@StefanLindner,是的,但它不起作用:(你检查过了吗?@Subala谢谢!我再次检查过。
javax.swing.SwingUtilities.invokeLater(…)
有效,而
scrollPanel.getVerticalScrollBar().setValue(0)
无效。你知道为什么吗?