Lớp Font dùng để thiết lập font màn hình và ánh xạ ký tự ngôn ngữ đến glyph tương ứng, trong khi FontMetrics định nghĩa đối tượng font metrics, đóng gói thông tin về việc render một font cụ thể trên màn hình cụ thể.
Font
Lớp Font tạo instance Font object để thiết lập font cho vẽ văn bản, label, text field, button, v.v. Font được chỉ định bằng tên, kiểu, cỡ.
Font có family name, logical name và face name:
- family name: Tên chung của font, ví dụ Courier.
- logical name: Chỉ định loại font, ví dụ Monospaced.
- face name: Chỉ định font cụ thể, ví dụ Courier Italic.
Ví dụ Font
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);
}
}
Kết quả

FontMetrics
Lớp FontMetrics trả về các tham số cụ thể cho một đối tượng Font. Object FontMetrics tạo bằng phương thức getFontMetrics(). Các phương thức bytesWidth(), charWidth(), charsWidth(), getWidth(), stringWidth() dùng để xác định chiều rộng văn bản tính bằng pixel. Các phương thức này thiết yếu để xác định vị trí ngang của văn bản trên màn hình.
Ví dụ FontMetrics
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);
}
}
Kết quả
