Java中的Font和FontMetrics有什么区别?
Font 类用于设置屏幕字体,它将语言字符映射到其各自的字形,而 FontMetrics 类定义一个字体度量对象,该对象封装了特定字体在特定屏幕上渲染的信息。
Font
Font 类可用于创建 Font 对象 的实例,以设置绘制文本、标签、文本字段、按钮等的字体,并且可以通过其名称、样式和大小来指定。
字体具有族名、逻辑名和面名
- 族名:它是字体的通用名称,例如 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 类用于返回特定 Font 对象的特定参数。FontMetrics 类的对象是使用 getFontMetrics() 方法创建的。FontMetrics 类的函数可以访问 Font 对象实现的详细信息。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);
}
}输出
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP