Ask Questions?

View Latest Questions



JPanel - Drawing Area
Posted on: July 26, 2006 at 12:00 AM
Define a new class that extends JPanel and define a paintComponent method in it.

Java: JPanel - Drawing Area


To use a JPanel for graphics


  1. Define a new class that extends JPanel and define a paintComponent method in it.
  2. Create an instance of the class and add it to a panel.


Example of drawing panel drawing area.


Define a subclass of JPanel and override paintComponent()


Create a subclass of JPanel to override its paintComponent() method.


It may be more convenient to define this class inside of your outer class so that it can access instance variables (fields) in the outer class.


For example,


. . .
class MyDrawing extends JPanel {
    . . .  // Methods, constructors, fields.
    public void paintComponent(Graphics g) {
         super.paintComponent(g);    // paints background
         . . .  // do your drawing here


The first line in paintComponent() is usually a call to the parent class's paintComponent() method (super refers to the parent class). The call to the parent's method may be omitted if the entire background is drawn by your version of paintComponent() so that it appears opaque, but it's probably best to make the call to avoid what Sun calls "visual artifacts".

Override paintComponent() rather than paint()

You sometimes see code that overrides paint() instead of paintComponent(). This was necessary in the older AWT, however in Swing paint() calls three methods: paintComponent(), paintBorder(), and paintChildren. It is therefore better to override paintComponent() to allow borders, altho you will not notice a difference in most cases.

Using the new class on a layout

When you create your GUI (usually in a constructor) create a new drawing panel object and add it to a container (the content pane or another panel). For example (assuming content is a content pane or a panel).

    . . .
MyDrawing drawing = new MyDrawing();

Repaint the panel after changes

Whenever the drawing needs to be changed because a value in the program has changed, call the panel's repaint() method. Often a listener (for a button, menu item, timer, ...) changes a value, then calls repaint(), which (eventually) calls your paintComponent() method. For example,

. . . // After anything changes that should appear in graphics
Copyleft 2003 Fred Swartz MIT License