Java Reference
In-Depth Information
Component Pieces
The
JComponent
class defines many aspects of AWT components that go above and beyond the
capabilities of the original AWT component set. This includes customized painting behavior
and several different ways to customize display settings, such as colors, fonts, and any other
client-side settings.
Painting JComponent Objects
Because the Swing
JComponent
class extends from the
Container
class, the basic AWT painting
model is followed: All painting is done through the
paint()
method, and the
repaint()
method
is used to trigger updates. However, many tasks are done differently. The
JComponent
class opti-
mizes many aspects of painting for improved performance and extensibility. In addition, the
RepaintManager
class is available to customize painting behavior even further.
■
Note
The
public void update(Graphics g)
method, inherited from
Component
, is never invoked
on Swing components.
To improve painting performance and extensibility, the
JComponent
splits the painting
operation into three tasks. The
public void paint(Graphics g)
method is subdivided into three
separate
protected
method calls. In the order called, they are
paintComponent(g)
,
paintBorder(g)
,
and
paintChildren(g)
, with the
Graphics
argument passed through from the original
paint()
call. The component itself is first painted through
paintComponent(g)
. If you want to customize
the painting of a Swing component, you override
paintComponent()
instead of
paint()
. Unless
you want to completely replace all the painting, you would call
super.paintComponent()
first,
as shown here, to get the default
paintComponent()
behavior.
public class MyComponent extends JPanel {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Customize after calling super.paintComponent(g)
}
...
}
■
Note
When running a program that uses Swing components in Java 5.0, the
Graphics
argument passed
to the
paint()
method and on to
paintComponent()
is technically a
Graphics2D
argument. Therefore,
after casting the
Graphics
argument to a
Graphics2D
object, you could use the Java 2D capabilities of the
platform, as you would when defining a drawing
Stroke
,
Shape
, or
AffineTransform
.