2

Why is it so terrible to override the paint() method of a top-level container like JFrame? What kind of problems can it cause?

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
moonbeamer2234
  • 351
  • 1
  • 3
  • 12

1 Answers1

4

There are a number of reasons, but many will also depend on the toolkit you are using.

Generally speaking, using paint on a top level container locks you into a given container (ie Frame or Applet). This also effects you ability to reuse the component, as windows can't be added to another window.

The other issue is that most frames have borders added to them (the frames border which usually holds the title and frame controls). Painting to the top level container does not take into consideration these insets, meaning that if you paint at location 0x0, you will be painting under the title bar of the frame.

Under Swing, top level containers are not double buffered. This means that repaints tend to flicker as each element is rendered directly to graphics layer individual, rather then being painted in a single pass.

Also in Swing, the top level containers are controlled by a JRootPane, which places a content pane (and if you're using it, menu bar) on-top of the container. This means that it is possible for your painting efforts to overridden by these components.

I would also add (under swing) that the component paint layer/chain is more flexible, allowing you the opportunity to paint at different layers, although generally speaking, you should be using paintComponent.

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366