如何獲取 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