Froxx
Froxx

Reputation: 1077

Why does setContentPane() not contain repaint()?

I'm wondering about this for quite a long time now.

I usually build my SWING programs by having a JFrame with a JPanel containing the window's content set as the content pane by setContentPane(). When I want my content to be replaced by another one (e.g. for getting a new mask after clicking a button) I call setContentPane() again and replace the content pane by another panel. But everytime I do this, I need to call repaint() after setContentPane() to make the change visible, so I created an own class I use for creating frames. This class extends JFrame and overrides setContentPane() like this:

@Override
public void setContentPane(Container c) {
  super.setContentPane(c);
  revalidate();
  repaint();
}

Why is this not implemented in the default JFrame class? Do I maybe have a bad side effect by doing this?

Upvotes: 3

Views: 1017

Answers (1)

Andrei Vajna II
Andrei Vajna II

Reputation: 4842

I think it's for the same reason it is not called after adding or removing components from a Container. Setting the content pane would be the same as adding components to the already existing one. The component hierarchy becomes invalid, so you have to call revalidate() and repaint().

And the reason why it is not called automatically, is suggested in the documentation for Container.validate():

Validating the container may be a quite time-consuming operation. For performance reasons a developer may postpone the validation of the hierarchy till a set of layout-related operations completes, e.g. after adding all the children to the container.

But this is just my guess.

Upvotes: 4

Related Questions