How to maintain JScrollPane position after executing JFrame.pack ()?

I have the following code:

JFrame frame = new JFrame();
JScrollPane scrollPane = new JScrollPane(new panel(with stuff in it));
frame.getContentPane().add(scrollPane);

So, the user scrolls a bit, and then clicks the link in my panel, and then I make the package (), so I try the following code:

int val = scrollPane.getVerticalScrollBar().getValue();
frame.pack();
scrollPane.getVerticalScrollBar().setValue(val);

But this code still brings my scrollBar back to the beginning, instead of keeping the position it was originally in before the package. Any ideas would be appreciated, thanks!

+3
source share
1 answer

Try wrapping the setValue () method in SwingUtilities.invokeLater ().

+3
source

All Articles