paintComponent
method in it.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 } }
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".
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.
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);
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();