Java Reference
In-Depth Information
3G.1 Introduction to Graphics
Java's original graphical tools were collectively known as the Abstract Window
Toolkit (AWT). The classes associated with the AWT reside in the package java.awt .
In order to create graphical programs like the ones you'll see in this section, you'll
need to include the following import declaration at the top of your programs:
import java.awt.*; // for graphics
To keep things simple, we'll use a custom class called DrawingPanel that was
written by the authors of this textbook to simplify some of the more esoteric details
of Java graphics. Its core code is less than a page long, so we aren't hiding much. You
won't need to import DrawingPanel , but you will need to place the file
DrawingPanel.java in the same folder as your program.
The drawing panel keeps track of the overall image, but the actual drawing will be
done with an object of type Graphics . The Graphics class is also part of the
java.awt library.
DrawingPanel
You can create a graphical window on your screen by constructing a DrawingPanel
object. You must specify the width and height of the drawing area. When the follow-
ing line executes, a window appears immediately on the screen:
DrawingPanel <name> = new DrawingPanel(<width>, <height>);
DrawingPanel objects have two public methods, listed in Table 3G.1.
The typical way that you'll use DrawingPanel will be to construct a panel of a
particular height and width, set its background color (if you don't want the default
white background), and then draw something on it using its Graphics object. The
DrawingPanel appears on the screen at the time that you construct it.
All coordinates are specified as integers. Each (x, y) position corresponds to a dif-
ferent pixel on the computer screen. The word pixel is shorthand for “picture ele-
ment” and represents a single dot on the computer screen.
Pixel
A single small dot on a computer screen.
Table 3G.1
Useful Methods for DrawingPanel
Method
Description
returns a Graphics object that can be used to draw onto the
panel
getGraphics()
sets the background color of the panel to the given color (the
default is white)
setBackground(color)
 
 
Search WWH ::




Custom Search