Java Reference
In-Depth Information
// Use the string width to find the starting point
int msg - x = getSize ().width/2 β€” msg - width/2;
// Use the vertical height of this font to find
// the vertical starting coordinate
int msg - y = getSize ().height/2 β€” descent/2 + ascent/2;
g.drawString (msg, msg - x, msg - y);
} // paintComponent
} // class DrawTextPanel
Note that if the paintComponent() method does not draw over the entire
surface, it should first invoke super.paintComponent() ,which will cause
the super class component to draw itself. For a JPanel , this would result in
filling the area with its current background color.
6.8 Drawing in the Java 2D API
The Java 2D drawing capabilities are extensive so we only have space here for
a brief introduction. We focus on the general techniques while the Web Course
Chapter 6 provides additional discussion and numerous example programs.
6.8.1 Drawing setup
We saw with the Graphics class that, prior to a drawing operation, the color
can be set for the β€œpen” that draws a line or fills a shape. Similarly the font can be
selected before invoking the drawString() method. With Graphics2D this
type of preparatory setup is taken to a much higher level. Several conditions can
be defined that determine the features of the subsequent drawing operation.
6.8.1.1 Paint
Before a drawing operation you define the paint that it will use with the set-
Paint() method. The paint could be a color but it could also be a gradient
between two colors or a texture made by tiling an image:
public void paintComponent (Graphics g) {
Graphics2D g2 = (Graphics2d) g;
g2.setPaint (Color.RED);
draw operation ...
Gradient gradient = new Gradient
(x1, y1, Color.YELLOW, x2, y2, Color.GREEN, true);
g2.setPaint (gradient)
draw operation ...
}
 
Search WWH ::




Custom Search