Java Reference
In-Depth Information
LISTING 13.1
Continued
15: public static void main(String[] arguments) {
16: if (arguments.length < 1) {
17: System.out.println(“Usage: java TextFrame message font”);
18: System.exit(-1);
19: }
20: TextFrame frame = new TextFrame(arguments[0], arguments[1]);
21: }
22:
23: }
24:
25: class TextFramePanel extends JPanel {
26: String text;
27: String fontName;
28:
29: public TextFramePanel(String text, String fontName) {
30: super();
31: this.text = text;
32: this.fontName = fontName;
33: }
34:
35: public void paintComponent(Graphics comp) {
36: super.paintComponent(comp);
37: Graphics2D comp2D = (Graphics2D)comp;
38: comp2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
39: RenderingHints.VALUE_ANTIALIAS_ON);
40: Font font = new Font(fontName, Font.BOLD, 18);
41: FontMetrics metrics = getFontMetrics(font);
42: comp2D.setFont(font);
43: int x = (getSize().width - metrics.stringWidth(text)) / 2;
44: int y = getSize().height / 2;
45: comp2D.drawString(text, x, y);
46: }
47: }
The TextFrame application takes two command-line arguments: the text to display and
the name of the font to use. Here's an example:
java TextFrame “Able was I ere I saw Elba” “Times New Roman”
Figure 13.2 shows how this looks on a system with the Times New Roman font installed.
When you run the application, resize the frame window to see how the text moves so that
it remains centered.
The TextFrame application consists of two classes: a frame and a panel subclass called
TextFramePanel . The text is drawn on the panel by overriding the paintComponent
( Graphics ) method and calling drawing methods of the Graphics2D class inside the
method.
 
Search WWH ::




Custom Search