Java Reference
In-Depth Information
The first statement in main constructs a DrawingPanel with a width of 200 and
a height of 100. Once it has been constructed, the window will pop up on the
screen. The second statement draws a line from (25, 75) to (175, 25). The first
point is in the lower-left part of the window (25 over from the left, 75 down from
the top). The second point is in the upper-right corner (175 over from the left, 25
down from the top).
Notice these particular lines of code:
Graphics g = panel.getGraphics();
g.drawLine (25, 75, 175, 25);
You might wonder why you can't just say:
panel.drawLine(25, 75, 175, 25);
// this is illegal
The problem is that there are two different objects involved in this program: the
DrawingPanel itself (the canvas) and the Graphics object associated with the panel
(the paintbrush). The panel doesn't know how to draw a line; only the Graphics
object knows how to do this. You have to be careful to make sure that you are talking
to the right object when you give a command.
This requirement can be confusing, but it is common in Java programs. In fact, in
a typical Java program, there are hundreds (if not thousands) of objects interacting
with each other. These interactions aren't so unlike interactions between people. If
you want to schedule a meeting, a busy corporate executive might tell you, “Talk to
my secretary about that.” Or if you're asking difficult legal questions, a person might
tell you, “Talk to my lawyer about that.” In this case, the DrawingPanel doesn't
know how to draw, so if it could talk it would say, “Talk to my Graphics object
about that.”
It's also legal to use the Graphics object without storing it in a variable, like
this:
panel.getGraphics().drawLine(25, 75, 175, 25); // also legal
But you'll often want to send several commands to the Graphics object, so it's
more convenient to give it a name and store it in a variable.
Let's look at a more complicated example:
1 // Draws three lines to make a triangle.
2
3 import java.awt.*;
4
5 public class DrawLine2 {
6
public static void main(String[] args) {
7
DrawingPanel panel = new DrawingPanel(200, 100);
8
Search WWH ::




Custom Search