Java Reference
In-Depth Information
Example 11•1: GraphicsSampler.java (continued)
}
// Draw and fill the polygon
g.setColor(fill);
g.fillPolygon(xpoints, ypoints, numpoints);
g.setColor(outline);
g.drawPolygon(xpoints, ypoints, numpoints);
centerText("fillPolygon()", "drawPolygon()", g, textcolor,
225, 210, 150, 80);
// Draw a 3D rectangle (clear an area for it first)
g.setColor(fill);
g.fillRect(20, 305, 160, 90);
g.draw3DRect(25, 310, 150, 80, true);
g.draw3DRect(26, 311, 148, 78, true);
g.draw3DRect(27, 312, 146, 76, true);
centerText("draw3DRect()", "x 3", g, textcolor, 25, 310, 150, 80);
// Draw an image (centered within an area)
int w = image.getWidth(this);
int h = image.getHeight(this);
g.drawImage(image, 225 + (150-w)/2, 310 + (80-h)/2, this);
centerText("drawImage()", null, g, textcolor, 225, 310, 150, 80);
}
// Utility method to tile an image on the background of the component
protected void tile(Graphics g, Component c, Image i) {
// Use bounds() instead of getBounds() if you want
// compatibility with Java 1.0 and old browsers like Netscape 3
Rectangle r = c.getBounds();
// How big is the component?
int iw = i.getWidth(c);
// How big is the image?
int ih = i.getHeight(c);
if ((iw <= 0) || (ih <= 0)) return;
for(int x=0; x < r.width; x += iw) // Loop horizontally
for(int y=0; y < r.height; y += ih) // Loop vertically
g.drawImage(i, x, y, c);
// Draw the image
}
// Utility method to center two lines of text in a rectangle.
// Relies on the FontMetrics obtained in the init() method.
protected void centerText(String s1, String s2, Graphics g, Color c,
int x, int y, int w, int h)
{
int height = metrics.getHeight(); // How tall is the font?
int ascent = metrics.getAscent(); // Where is the font baseline?
int width1=0, width2 = 0, x0=0, x1=0, y0=0, y1=0;
width1 = metrics.stringWidth(s1); // How wide are the strings?
if (s2 != null) width2 = metrics.stringWidth(s2);
x0 = x + (w - width1)/2;
// Center the strings horizontally
x1 = x + (w - width2)/2;
if (s2 == null) // Center one string vertically
y0 = y + (h - height)/2 + ascent;
else { // Center two strings vertically
y0 = y + (h - (int)(height * 2.2))/2 + ascent;
y1 = y0 + (int)(height * 1.2);
}
g.setColor(c);
// Set the color
g.drawString(s1, x0, y0);
// Draw the strings
Search WWH ::




Custom Search