Java Reference
In-Depth Information
1
// Fig. 13.11: FontJPanel.java
2
// Display strings in different fonts and colors.
3
4
import
java.awt.Font;
import
java.awt.Color;
5
import
java.awt.Graphics;
6
import
javax.swing.JPanel;
7
8
public
class
FontJPanel
extends
JPanel
9
{
10
// display Strings in different fonts and colors
11
@Override
12
public
void
paintComponent(Graphics g)
13
{
14
super.paintComponent(g);
15
16
// set font to Serif (Times), bold, 12pt and draw a string
17
g.setFont(
new
Font(
"Serif"
,
Font.BOLD
,
12
));
18
g.drawString(
"Serif 12 point bold."
,
20
,
30
);
19
20
// set font to Monospaced (Courier), italic, 24pt and draw a string
21
g.setFont(
new
Font(
"Monospaced"
,
Font.ITALIC
,
24
));
22
g.drawString(
"Monospaced 24 point italic."
,
20
,
50
);
23
24
// set font to SansSerif (Helvetica), plain, 14pt and draw a string
25
g.setFont(
new
Font(
"SansSerif"
,
Font.PLAIN
,
14
));
26
g.drawString(
"SansSerif 14 point plain."
,
20
,
70
);
27
28
// set font to Serif (Times), bold/italic, 18pt and draw a string
29
g.setColor(
Color.RED
);
30
g.setFont(
new
Font(
"Serif"
,
Font.BOLD
+
Font.ITALIC
,
18
));
g.getFont().getName()
31
g.drawString(
+
" "
+
g.getFont().getSize()
+
32
" point bold italic."
,
20
,
90
);
33
}
34
}
// end class FontJPanel
Fig. 13.11
|
Display strings in different fonts and colors.
1
// Fig. 13.12: Fonts.java
2
// Using fonts.
3
import
javax.swing.JFrame;
4
5
public
class
Fonts
6
{
7
// execute application
8
public
static
void
main(String[] args)
9
{
10
// create frame for FontJPanel
11
JFrame frame =
new
JFrame(
"Using fonts"
);
12
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE
);
13
14
FontJPanel fontJPanel =
new
FontJPanel();
15
frame.add(fontJPanel);
Fig. 13.12
|
Using fonts. (Part 1 of 2.)