Basic Graphics Components in Java Applets


The Graphics class is actually java.awt.Graphics, which is why the above examples had to include the "import java.awt.*;" line. All applet have a Graphics object associated with them. Many other objects in Java's class library have associated Graphics objects. It is by using these Graphics objects, that we do all graphical output. Let's look at a few of the more useful methods in Graphics.

MethodWhat it does
clearRect(int x, int y, int width, int height) Clears a rectangular area width x height, with the upper left corner at (x,y)
drawLine(int x1, int y1, int x2, int y2) Draws a line from (x1,y1) to (x2,y2)
drawOval(int x, int y, int width, height) Draws an oval with width width and height height, with it's center at (x,y)
drawRect(int x, int y, int width, int height) Draw a rectangle width x height, with the upper left corner at (x,y)
drawSting(String str, int x, int y) Prints str on the screen starting a little above (x,y)
fillOval(int x, int y, int width, height) Draws a filled oval. Uses same parameters as drawOval
fillRect(int x, int y, int width, height) Draws a filled rectangle. Uses same parameters as drawRect
getColor() Returns the current color being used in the Graphics object
getFont() Returns the current font being used in the Graphics object
setColor(Color c) Sets the current color being used in the Graphics object
setFont(Font font) Sets the current font being used in the Graphics object