Using Graphics
This isn't meant as a knock to those of us who enjoy displaying arrays, incrementing variables, or using a constructor method, but let's face it—many subjects in a programming language such as Java tend to be dry.
It's hard to impress your non-programming acquaintances with the way your if-else statement determines which method to use in a mathematical application. When you're on a first date, you won't get far with the anecdote that illustrates how a switch-case block statement handles a variety of circumstances correctly. Nobody ever made a movie about the ternary operator.
Graphics programming is the exception to the rule. When you write a program that does something interesting with graphics, you can have fun with a programming language and impress relatives, friends, and prospective employers at the same time.
Drawing things such as lines and polygons is as easy in a Java program as displaying text. All you need are Graphics and Graphics2D objects to define the drawing surface and objects that represent the things to draw.
The Graphics class stores information required to display something onscreen. The most common use of the class is as an object that represents the area where something can be drawn in a container such as a panel or an applet window.
In a container such as a JPanel component, a Graphics object is sent to the paintComponent() method as an argument:
public void paintComponent(Graphics comp) {
// ...
}
The same thing happens in the paint() method of an applet:
public void paint(Graphics comp) {
// ...
}
Both of these methods are called automatically whenever the container must be redrawn. For instance, if you have a Java frame open as an application is running and cover it up with another window, the frame's paintComponent() method will be called when the other window is closed.
Inside these paint methods, you should begin by calling the same method in the superclass, as in the following example:
public void paintComponent(Graphics comp) {
super.paintComponent(comp);
}
Next, the Graphics object argument can be used to create a Graphics2D object, as in the following statement:
Graphics2D comp2D = (Graphics2D) comp;
Once you have a Graphics2D object, you draw by calling its methods. This Graphics2D object, which is called comp2D in this hour's projects, has methods used to draw text with a command such as the following:
comp2D.drawString("Draw, pardner!", 15, 40);
This statement causes the text Draw, pardner! to be displayed at the (x,y) coordinates of (15,40).
All of the shape- and line-drawing methods work using the same (x,y) coordinate system as text. The (0,0) coordinate is at the upper-left corner of the container. The x values go up as you head to the right, and y values go up as you head downward. You can determine the maximum (x,y) value you can use in an applet with the following statements:
int maxXValue = getSize().width;
int maxYValue = getSize().height;
|