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 Graphics2D
object to define the drawing surface and objects that represent things to draw.
The Graphics2D
object has methods used to draw text with a command such as the following:
comp2D.drawString("Draw, pardner!", 15, 40);
This draws the text “Draw, pardner!” at the coordinates (15,40). Drawing methods use the same (x,y) coordinate system as text. The (0,0) coordinate is at the upper-left corner of the container, x values increase to the right, and y values increase as you go down. You can determine the maximum (x,y) value you can use in an applet with the following statements:
int maxXValue = getSize().
Get Sams Teach Yourself Java™ in 24 Hours, Sixth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.