Getting the Dimensions of Text:获取文本的长和宽

来源:互联网 发布:mac电脑照片怎么整理 编辑:程序博客网 时间:2024/04/29 06:36

// From within the paint() method.

public void paint(Graphics g) {

Graphics2D g2d = (Graphics2D)g;

Font font = new Font("Serif", Font.PLAIN, 12);

FontMetrics fontMetrics = g2d.getFontMetrics();

int width = fontMetrics.stringWidth("aString");

int height = fontMetrics.getHeight();

}

// From within a component.

class MyComponent extends JComponent {

MyComponent() {

Font font = new Font("Serif", Font.PLAIN, 12);

FontMetrics fontMetrics = getFontMetrics(font);

int width = fontMetrics.stringWidth("aString");

int height = fontMetrics.getHeight();

}

}

原创粉丝点击