Java: JPanel - Drawing Area
To use a JPanel for graphics
- Define a new class that extends JPanel and define
a
paintComponent
method in it. - Create an instance of the class and add it to a panel.
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. @Override public void paintComponent(Graphics g) { super.paintComponent(g); // paints background . . . // do your drawing here } }
super.paintComponent()
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
. The general rule is to override paintComponent()
if you're using Swing (JComponent, JPanel, JApplet) and paint()
if you're using one of the AWT classes (Applet, Canvas).
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(); content.add(drawing);
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 drawing.repaint();