Java中的Font和FontMetrics有什么区别?

What are the differences between a Font and a FontMetrics in Java?

字形

Fontclass可用于创建Font对象的实例,以设置用于绘制文本,标签,文本字段,按钮等的字体,并且可以通过其名称,样式和大小来指定它。

字体具有姓,逻辑名和面孔名

  • 家族名称:它是字体的通用名称,例如Courier。
  • 逻辑名称:它指定字体的类别,例如Monospaced。
  • 人脸名称:它指定特定的字体,例如Courier Italic。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.awt.*;
import javax.swing.*;
public class FontTest extends JPanel {
 public void paint(Graphics g) {
   g.setFont(new Font("TimesRoman", Font.BOLD, 15));
   g.setColor(Color.blue);
   g.drawString("Welcome to Tutorials Point", 10, 20);
 }
 public static void main(String args[]) {
   JFrame test = new JFrame();
   test.getContentPane().add(new FontTest());
   test.setTitle("Font Test");
   test.setSize(350, 275);
   test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   test.setLocationRelativeTo(null);
   test.setVisible(true);
 }
}

输出量

字体指标

FontMetrics类用于返回特定Fontobject的特定参数。使用getFontMetrics()方法创建FontMetricsclass的对象。 FontMetricsclass的方法可以提供对Fontobject实现的详细信息的访问。 bytesWidth(),charWidth(),charsWidth(),getWidth()和stringWidth()方法用于确定文本对象的宽度(以像素为单位)。这些方法对于确定文本在屏幕上的水平位置至关重要。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.awt.*;
import javax.swing.*;
public class FontMetricsTest extends JPanel {
 public void paint(Graphics g) {
   String msg ="Tutorials Point";
   Font f = new Font("Times New Roman",Font.BOLD|Font.ITALIC, 15);
   FontMetrics fm = getFontMetrics(f);
   g.setFont(f);
   int x =(getSize().width-fm.stringWidth(msg))/2;
   System.out.println("x="+x);
   int y = getSize().height/2;
   System.out.println("y="+y);
   g.drawString(msg, x, y);
 }
 public static void main(String args[]){
   JFrame test = new JFrame();
   test.getContentPane().add(new FontMetricsTest());
   test.setTitle("FontMetrics Test");
   test.setSize(350, 275);
   test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   test.setLocationRelativeTo(null);
   test.setVisible(true);
 }
}

输出量