Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

Drawing Lines and Shapes 329

public voidpaintComponent(Graphics comp) {
Graphics2D comp2D = (Graphics2D) comp;
comp2D.setColor(Color.orange);
comp2D.drawString(“Go, Buccaneers!”, 5, 50);
}


Unlike the setBackground()method, which you can call directly on a con-
tainer, you must call the setColor()method on a Graphics2Dobject.


Creating Custom Colors


You can create custom colors in Java by specifying their Standard Red
Green Blue (sRGB) value. sRGBdefines a color by the amount of red,
green, and blue present in the color. Each value ranges from 0 (none of that
color) to 255 (the maximum amount).


The constructor Color(int, int, int)takes arguments representing the
red, green, and blue values. The following code draws a panel that dis-
plays light orange text (230 red, 220 green, 0 blue) on a dark red (235 red,
50 green, 50 blue) background:


importjava.awt.;
importjavax.swing.
;


public classGoBucs extendsJPanel {
Color lightOrange= new Color(230, 220, 0);
Color darkRed= newColor(235, 50, 50);


public voidpaintComponent(Graphics comp) {
Graphics2D comp2D = (Graphics2D) comp;
comp2D.setColor(darkRed);
comp2D.fillRect(0, 0, 200, 100);
comp2D.setColor(lightOrange);
comp2D.drawString(“Go, Buccaneers!”, 5, 50);
}
}


This example calls the fillRect()method of Graphics2Dto draw a filled-
in rectangle using the current color.


Drawing Lines and Shapes


Drawing shapes such as lines and rectangles is as easy in a Java program
as displaying text. All you need is a Graphics2Dobject to define the draw-
ing surface and objects that represent things to draw.


NOTE
sRGB values enable the cre-
ation of 16.5 million possible
combinations,though most
computer monitors only offer a
close approximation for most of
them. For guidance on whether
burnt-midnight blue goes well
with medium-faded-baby green,
readSams Teach Yourself Color
Sense While Waiting in Line at
This Bookstore.
Free download pdf