Java Reference
In-Depth Information
In Supplement 3G, we introduced a graphical class called
DrawingPanel
. The
DrawingPanel
was simple enough that you did not need to learn a lot of details
about graphical user interfaces. Now that we're starting to uncover those details, we
can examine how to draw our own two-dimensional graphics manually. This will
help you eventually understand the code for
DrawingPanel
and even reimplement it
yourself.
Earlier in this chapter we discussed the
JPanel
component, which we used as an
invisible container for laying out other components. Panels have one other important
function: They serve as surfaces onto which we can draw. The
JPanel
object has a
method called
paintComponent
that draws the panel on the screen. By default this
method draws nothing, so the panel is transparent.
We can use inheritance to change the drawing behavior for a panel. If we want to
make a panel onto which we can draw shapes, we can extend
JPanel
and override
the
paintComponent
method. Here is the header of the
paintComponent
method
we must override:
public void paintComponent(Graphics g)
Its parameter,
Graphics g
, should look familiar to you if you read Supplement 3G.
Graphics
is a class in Java's
java.awt
package that has methods for drawing shapes,
lines, and images onto a surface. Think of the
Graphics
object as a pen and the panel
as a sheet of paper.
There is one quirk to keep in mind when you are writing a
paintComponent
method. Remember that when you override a method, you replace the superclass
method's previous functionality. We don't want to lose the behavior of
paintComponent
from
JPanel
, though, because it does important things for the panel; we just want to
add additional behavior to it. Therefore, the first thing you should do when you over-
ride
paintComponent
is to call
super.paintComponent
and pass it your
Graphics
object
g
as its parameter. (If you don't, you can get strange ghosty afterimages when
you drag or resize your window.)
Here's a small class that represents a panel with two rectangles drawn on it:
1 // A panel that draws two rectangles on its surface.
2
3
import
java.awt.*;
4
import
javax.swing.*;
5
6
public class
RectPanel
extends
JPanel {
7
public void
paintComponent(Graphics g) {
8
super
.paintComponent(g); // call JPanel's version
Search WWH ::
Custom Search