Project

General

Profile

FontSizeExample.java

Greg Shah, 08/27/2015 01:19 PM

Download (1.59 KB)

 
1
import javax.swing.*;
2
import java.awt.font.*;
3
import java.awt.event.*;
4
import java.awt.*;
5

    
6
public class FontSizeExample
7
{
8
   public static void main(String[] args)
9
   {
10
      SwingUtilities.invokeLater(new Runnable()
11
      {
12
         public void run()
13
         {
14
            final int ht = 300;
15
            final int wd = 900;
16
            
17
            JFrame frame = new JFrame("Font Sizing");
18
            frame.setSize(wd, ht);
19
            frame.setLocation(150, 150);
20
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
21
            
22
            frame.setContentPane(new JComponent()
23
            {
24
               public void paint(Graphics g)
25
               {
26
                  Graphics2D g2 = (Graphics2D) g;
27
                  
28
                  g2.fillRect(10, 10, 96, 96);
29
                  
30
                  Font   font = new Font(Font.SANS_SERIF, 0, 96);
31
                  String text = "WITM";
32
                  
33
                  g2.setFont(font);
34

    
35
                  FontMetrics fm = g2.getFontMetrics();
36
                  LineMetrics lm = fm.getLineMetrics(text, g2);
37
                  
38
                  double y = 10 + lm.getAscent();
39

    
40
                  g2.drawString(text, 130, (int) y);
41

    
42
                  int ht = fm.getHeight();
43
                  double lht = lm.getHeight();
44
                  
45
                  g2.setFont(new Font(Font.SANS_SERIF, 0, 16));
46
                  g2.drawString(String.format("textHeight = %d px (line metrics ht = %g px)", ht, lht), 130 + 30 + 265, 53);
47
               }
48
            });
49
            
50
            frame.setVisible(true);
51
         }
52
      });
53
   }
54
}