Search code examples
javaswingjpaneljscrollpane

dynamically adding components and calling repaint/validate/revalidate


I have a main JPanel, an inner JPanel and a JScrollPane for the inner JPanel

mainPanel = new JPanel();
innerPanel = new JPanel();
scroll = new JScrollPane(innerPanel);
scroll.setPreferredSize(new Dimension(400,300));
mainPanel.add(scroll);

I'm also adding components dynamically to the inner JPanel

After I add all the components I call revalidate() and repaint() on the inner JPanel

And when I call removeAll() components from the inner JPanel I call revalidate() and repaint() again on the inner JPanel

It works fine but my confusion and question is if I should call revalidate() on the scroll as well, ie:

scroll.getViewport().revalidate(); 

Thanks for any feedback.


Solution

  • Swing is smart. You call revalidate() on the component you changed.

    As the API says:

    In other words after this method is called, the first validateRoot (if any) found when walking up the containment hierarchy of this component will be validated. By default, JRootPane, JScrollPane, and JTextField return true from isValidateRoot.

    So revalidating() the scrollPane would be doing the work twice.

    You could revalidate() the scrollPane instead of the panel, but its easier to just revalidate() the panel because you have a reference to it because you just modified it.

    Start with the API when you have a question about a method. If there is something you don't understand then quote the reference from the API so we can help.