java界面中如何得到字符串的高度和宽度

来源:互联网 发布:传说 狐狸 知乎 编辑:程序博客网 时间:2024/05/22 11:09

代码如下:

 

public static void getStringBounds()
 {
  Font font = new Font(Font.SERIF,Font.BOLD,8);
  String text = "ABC";
  //方法1--只能分别得到字符串的宽度和高度
  FontMetrics fm = Toolkit.getDefaultToolkit().getFontMetrics(font);
  int width = SwingUtilities.computeStringWidth(fm, text);
  int height = fm.getHeight();
  
  System.out.println("方法1 width:" + width + " height:" + height);
  
  //方法2--能得到字符串的边界
  FontRenderContext frc = new FontRenderContext(new AffineTransform(),true,true);
  Rectangle rec = font.getStringBounds(text, frc).getBounds();
  
  System.out.println("方法2 width:" + rec.getWidth() + " height:" + rec.getHeight());
  
 }

原创粉丝点击