Colorful graphics and animation can change a dull, static, and gray Web page into an exciting and interesting place to visit. It's no wonder, then, that programming applets that display graphics and animation is one of the most popular uses of Java.
Java provides a wide range of tools for creating and displaying graphics. The majority of Java's graphics methods are contained in the Graphics class.
Using Java's Graphics Class
Java's Graphics class provides methods for manipulating a number of graphical features including the following:
Creating Graphics Primitives
Creating flicker-free animation
Graphics in Java is made relatively easy by many standard library calls that are not included in many languages. First and
foremost, you should know that in Java graphics programming, one of the most important instantiated objects is the graphics
context. This object is an instance of the java.awt.Graphics class, and it refers to an area of the screen such as an applet. A
graphics context provides methods for all of the drawing operations on its area. It also holds "contextual" information about
such things as the drawing area's clipping region, painting color, transfer mode, and text font. See Lesson 7
for a demonstration of which fonts your browser supports.
Most often the graphics context is obtained from the Java window manager as a result of a painting request. This context is
passed to your component's paint( ) or update( ) method. (Java also allows the user to obtain a graphics context for an
offscreen image, which enables you to do double buffering. It is not necessary that you know what double buffering means, but
you can find out from most any book on graphics and programming.)
The coordinate system is laid out with (0, 0) at the top left corner of the drawing area with the x's and y's increasing until they
get to the applet's width and height. The coordinates are measured in pixels, with x increasing horizontal to the right and y
increasing vertically down.
Below: Drawing a line using Java
Below: Drawing a rectangle using Java
Below: Drawing a rounded corner rectangle using Java
Below: Drawing a 3D rectangle using Java (very hard to see effect)
Below: Drawing a polygon using Java
Below: Drawing ovals using Java, including filling the object
Below: Drawing arcs using Java, including filling the object
Below is code that generates various shapes using Java. Remove the comments
from the paricular shape you wish to generate.
- Write a Java program using several of the above named shapes.
Return to the Top