How do I implement custom painting in Swing?

Scott Stanchfield

The trick is to not override a Swing component's paint() method...

Swing components (which are subclasses of JComponent) have a slightly different paint structure than AWT components. In AWT, you simply override the paint() method, adding your drawing commands.

In Swing, the paint() method of JComponent looks something like:

public void paint(Graphics g) {
  // deal with double buffering and paint optimization issues
  paintComponent();
  paintBorder();
  paintChildren();
}

This ensures that child components always appear on top of anything drawn by a container.

Normally, you should override paintComponent() to do your drawing.

If you do override paint() for some reason, make sure you call super.paint() as the first thing in your method. Note that this may not properly handle double buffering and paint optimizations that Swing does.

Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact