Java Reference
In-Depth Information
Displaying a
drawing
5
In this chapter we shall learn how a program can display a drawing in a panel. For
now, the drawing is predefined and cannot be altered by the user.
To display graphics we use panels as canvases. The whole rectangular area of a
panel can be used to draw on, no matter whether it is currently visible or not.
The central means for drawing is method
paintComponent
of class
JPanel
. This
method redraws the panel. It is automatically called by the runtime system when
necessary; for example, when the GUI is resized. All the commands to draw some-
thing into the panel should therefore be put into that method. More precisely we
!
override
paintComponent
to add our own commands.
It is important
never
to call
paintComponent
directly in order to initiate a
redrawing. To do that, one calls the
repaint()
-method of the panel. This is done
to avoid conflicts between redrawing and other operations of the runtime system.
A call to
repaint
does not immediately repaint a component. Instead it tells the
runtime system that one would like the component to be redrawn. The system
calls
paintComponent
after other pending actions have been completed; see also
Chapter 20.
■
5.1
Method
paintComponent
Method
paintComponent
of class
JPanel
has the following syntax:
public void
paintComponent(Graphics g)
It receives a parameter
g
of type
Graphics
. This is an abstract class from the AWT
library. A
Graphics
object connects the Java drawing commands to the actual
drawing mechanism of the current computer. The class
Graphics
also provides
methods to draw into a panel. As we will never call
paintComponent
directly,
we do not have to construct a
Graphics
object; this is done by the operating
system.
To add our own drawings to a panel we extend
paintComponent
by adding
graphics commands. To this end we
override
paintComponent
.Ofcourse we do
Search WWH ::
Custom Search