Graphics class -- defined in java.awt (abstract windowing toolkit) package
-It is used to draw shapes, lines, and strings.
Paint method in JApplet public void paint(Graphics page)
{
…
}
The paint method is invoked automatically whenever the graphic elements of the applet need to be painted to the screen.
Coordinate Systems
Cartesian coordinate system
Graphic system
(0,0)
x = 30
(x,y)
y=28
y
(x,y) = (30,28)
(0,0)
x
Some methods of the Graphics class: void drawRect(int x, int y, int width, int height) – paints a rectangle with upper left cornet (x,y) and dimensions width and height. void fillRect(int x, int y, int width, int height) – same as drawRect, but with inside filled with a foreground color. void drawOval(int x, int y, int width, int height) – paints an oval bounded by the rectangle with an upper left cornet of (x,y) and dimensions width and height. void fillOval(int x, int y, int width, int height) – same as drawOval, but with inside filled with a foreground color. void drawLine(int x1, int y1, int x2, int y2) – paints a line from point (x1,y1) and point (x2,y2). void drawString(String str, int x, int y) – paints the character string at point (x,y), extending to the right. void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) – paints an arc along the oval bounded by the rectangle defined by x, y width, and height. The arc starts at startAngle and extends for a distance defined by arcAngle (positive – counter clockwise). void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) – same as drawArc, but with inside filled with a foreground color. void setColor(Color color) – sets this graphics content’s foreground color to the specified color.
Color getColor() – returns this graphics content’s foreground color.
Drawing a rectangle: page.drawRect (50, 20, 100, 40);
50
X
20
40
100
Y
Drawing an oval: page.drawOval (175, 20, 50, 80);
175
X
20
80
bounding rectangle Y
50
Drawing a line: page.drawLine (10, 20, 150, 45); or page.drawLine (150, 45, 10, 20);
10
20
45
Y
150
X
Drawing an arc: page.drawArc (175, 20, 50, 80, 30, 90);
Arc is drawn
175
X
20
Arc angle
Start angle
90
30
bounding rectangle Y
50
80
//********************************************************************
// Einstein.java
// Demonstrates a basic applet.
//********************************************************************
import javax.swing.JApplet; import java.awt.Graphics; public class Einstein extends JApplet
{
//----------------------------------------------------------------// Draws a quotation by Albert Einstein among some shapes.
//----------------------------------------------------------------public void paint (Graphics page)
{
page.drawRect (50, 50,