Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force-refresh/repaint a JScrollPane?

I am adding lots of components (JPanels, JLabels etc.) into a JScrollPane programagically at the start of my program based on some stuff from a database.

It seems that this procedure is too fast for the GUI(?), so the JScrollPane does not always update correctly, i.e the scroll bars are not visible even though the inner JPanel is bigger than the visible area.

Resizing the Window (JFrame) fixes the problem, as I assume Java is re-printing the components when they are resized.

As a test, I have added a debug-button that I can click after the startup of the program has finished. I am trying to force the JScrollPane to "refresh" itself.

I have tried doing:

scrollpane.repaint();
scrollpane.validate();
scrollpane.revalidate();

None of them seems to work. However, if I change the border (or any other layout related to the JScrollPane), it refreshes correctly.

scrollpane.setBorder(new LineBorder(Color.RED));

So I basically have 2 questions.

  1. What is the command for forcing the scrollpane to "refresh"? Obviously it is doing some kind of "repaint" thing when I am adding the border. How can I run that only?

  2. Is there a way of "pausing" the printing of components as they are added and resume it again after I added all the wanted components? As it is now, I basically "see" the components being added on the screen (even though it is really fast). It would be better if I can add all the components I want and THEN tell the program to print it to the screen/JFrame.

like image 820
Daniele Testa Avatar asked Mar 19 '14 17:03

Daniele Testa


1 Answers

The basic code for adding components to a visible panel is:

panel.add(...);
panel.add(...);
panel.revalidate();
panel.repaint();

Adding a component does nothing because the component still has a zero size so there is nothing to paint. When you invoke the revalidate() method the layout manager gets invoked so components will now have a location/size. The repaint() will then paint the components. The revalidate() will also cause the scrollbars to show when required. This of course assumes you are using layout managers.

The components are added to the panel so you invoke the methods on the panel, not the scrollpane.

like image 183
camickr Avatar answered Nov 16 '22 16:11

camickr