Java Reference
In-Depth Information
Figure 3G.11
Output of DrawFonts
3G.2 Procedural Decomposition with Graphics
If you write complex drawing programs, you will want to break them down into sev-
eral static methods to structure the code and to remove redundancy. When you do
this, you'll have to pass the Graphics object to each static method that you intro-
duce. For a quick example, the DrawStringMessage1 program from the previous
section could be split into a main method and a drawText method, as follows:
1 // Draws a message several times using a static method.
2
3 import java.awt.*;
4
5 public class DrawStringMessage2 {
6
public static void main(String[] args) {
7
DrawingPanel panel = new DrawingPanel(200, 100);
8
panel.setBackground(Color.YELLOW);
9
10
Graphics g = panel.getGraphics();
11
drawText(g);
12
}
13
14
public static void drawText(Graphics g) {
15
for ( int i = 0; i < 10; i++) {
16
g.drawString("There is no place like home",
17
i * 5, 10 + i * 10);
18
}
19
}
20 }
This program produces the same output as the original program (Figure 3G.10).
The program wouldn't compile without passing Graphics g to the drawText method,
because g is needed to call drawing methods such as drawString and fillRect .
 
 
Search WWH ::




Custom Search