Font ใช้ตั้งค่าฟอนต์หน้าจอ และแมปตัวอักษรของภาษาไปยัง glyphs ของมัน ในขณะที่ FontMetrics กำหนดอ็อบเจกต์เมตริกฟอนต์ ซึ่งห่อหุ้มข้อมูลเกี่ยวกับการแสดงผลของฟอนต์เฉพาะบนหน้าจอเฉพาะ
Font
Font ใช้สร้างอินสแตนซ์ของ Font object เพื่อตั้งค่าฟอนต์สำหรับ การวาดข้อความ, Label, Text Field, ปุ่ม เป็นต้น และระบุโดย ชื่อ, สไตล์, และขนาด
ฟอนต์มีชื่อครอบครัว ชื่อตรรกะ และชื่อหน้า
- Family name: ชื่อทั่วไปของฟอนต์ เช่น Courier
- Logical name: ระบุหมวดหมู่ฟอนต์ เช่น Monospaced
- Face name: ระบุฟอนต์เฉพาะ เช่น Courier Italic
ตัวอย่าง 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);
}
}
ผลลัพธ์

FontMetrics
FontMetrics ใช้คืนค่าพารามิเตอร์เฉพาะสำหรับ Font object อ็อบเจกต์ FontMetrics สร้างด้วยเมธอด getFontMetrics() เมธอดของ FontMetrics ให้รายละเอียดการใช้งาน Font เมธอด bytesWidth(), charWidth(), charsWidth(), getWidth(), stringWidth() ใช้หาความกว้างของข้อความในพิกเซล สำคัญสำหรับกำหนดตำแหน่งแนวนอนของข้อความบนหน้าจอ
ตัวอย่าง 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);
}
}
ผลลัพธ์
