-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFontTest.java
86 lines (65 loc) · 2.08 KB
/
FontTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package font;
import javax.swing.*;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
/**
* @author Cay Horstmann
* @version 1.34 2015-05-12
*/
public class FontTest {
public static void main(String[] args) {
EventQueue.invokeLater(() ->
{
JFrame frame = new FontFrame();
frame.setTitle("FontTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
/**
* A frame with a text message component
*/
class FontFrame extends JFrame {
public FontFrame() {
add(new FontComponent());
pack();
}
}
/**
* A component that shows a centered message in a box.
*/
class FontComponent extends JComponent {
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 200;
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
String message = "Hello World!";
Font font = new Font("Serif", Font.BOLD, 36);
g2.setFont(font);
// measure the size of the message
FontRenderContext context = g2.getFontRenderContext();
;
Rectangle2D bounds = font.getStringBounds(message, context);
// set (x, y) = top left of the text
double x = (getWidth() - bounds.getWidth());
double y = (getHeight() - bounds.getHeight());
// add ascent to y to reach the baseline
double ascent = -bounds.getY();
double baseY = y + ascent;
// draw the message
g2.drawString(message, (int) x, (int) baseY);
g2.setPaint(Color.LIGHT_GRAY);
// draw the baseline
g2.draw(new Line2D.Double(x, baseY, x + bounds.getWidth(), baseY));
// draw the enclosing rectangle
Rectangle2D rectangle2D = new Rectangle2D.Double(x, y, bounds.getWidth(), bounds.getHeight());
g2.draw(rectangle2D);
}
public Dimension getPreferredSize() {
return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT);
}
}