A แบบอักษร คลาสใช้เพื่อตั้งค่าแบบอักษรของหน้าจอและจับคู่อักขระของภาษากับร่ายมนตร์ตามลำดับ ในขณะที่ FontMetrics class กำหนดอ็อบเจ็กต์เมตริกฟอนต์ ซึ่งสรุปข้อมูลเกี่ยวกับการแสดงฟอนต์เฉพาะบนหน้าจอเฉพาะ
แบบอักษร
แบบอักษร คลาสสามารถใช้เพื่อสร้างอินสแตนซ์ของ อ็อบเจกต์ฟอนต์ เพื่อกำหนดแบบอักษรสำหรับ การวาดข้อความ ป้ายกำกับ ช่องข้อความ ปุ่ม ฯลฯ และสามารถระบุได้ด้วย ชื่อ ลักษณะ และขนาด
แบบอักษรมีชื่อสกุล ชื่อตรรกะ และชื่อใบหน้า
- นามสกุล: เป็นชื่อทั่วไปของฟอนต์ เช่น Courier
- ชื่อตรรกะ :ระบุหมวดหมู่ของฟอนต์ เช่น Monospaced
- ชื่อใบหน้า :ระบุแบบอักษรเฉพาะ เช่น Courier Italic
ตัวอย่าง
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 คลาสใช้เพื่อส่งคืนพารามิเตอร์เฉพาะสำหรับ แบบอักษร วัตถุ. วัตถุของ FontMetrics คลาสถูกสร้างขึ้นโดยใช้ getFontMetrics() กระบวนการ. วิธีการของ FontMetrics คลาสสามารถให้การเข้าถึงรายละเอียดของการใช้งาน แบบอักษร วัตถุ. วิธีการ bytesWidth(), charWidth(), charsWidth(), getWidth(), และ stringWidth() ใช้เพื่อกำหนดความกว้างของวัตถุข้อความเป็นพิกเซล วิธีการเหล่านี้จำเป็นสำหรับการกำหนดตำแหน่งแนวนอนของข้อความบนหน้าจอ
ตัวอย่าง
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);
}
} ผลลัพธ์
