如何获取 Java Swing 中的字体指标?
要获取字体指标,请使用 FontMetrics 类
Graphics2D graphics = (Graphics2D) gp.create(); String str = getWidth() + "(Width) x (Height)" + getHeight(); FontMetrics m = graphics.getFontMetrics();
现在要显示它
int xValue = (getWidth() - m.stringWidth(str)) / 2; int yValue = ((getHeight() - m.getHeight()) / 2) + m.getAscent(); graphics.drawString(str, xValue, yValue);
以下是获取 Java Swing 中字体指标的一个示例
示例
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SwingDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("Font Metrics");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new Demo());
frame.pack();
frame.setVisible(true);
System.out.println(frame.getSize());
}
}
class Demo extends JPanel {
@Override
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
@Override
protected void paintComponent(Graphics gp) {
super.paintComponent(gp);
Graphics2D graphics = (Graphics2D) gp.create();
String str = getWidth() + "(Width) x (Height)" + getHeight();
FontMetrics m = graphics.getFontMetrics();
int xValue = (getWidth() - m.stringWidth(str)) / 2;
int yValue = ((getHeight() - m.getHeight()) / 2) + m.getAscent();
graphics.drawString(str, xValue, yValue);
graphics.dispose();
}
}输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP