java获取一个字符串在屏幕上的尺寸的方法

如下面的例子所示

代码:

package test3;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class StringTest extends JFrame {

	public StringTest(){
		this.setSize(300,300);
		this.setLayout(null);
		this.setTitle("字符串尺寸测试");
		
		MyPanel mp=new MyPanel();
		mp.setSize(200,200);
		mp.setLocation(30,30);
		this.add(mp);
		mp.setBackground(Color.pink);
		
		this.setVisible(true);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	
	class MyPanel extends JPanel{
		public MyPanel(){
			
		}
		
		public void paint(Graphics gs){
			super.paint(gs);
			Graphics2D g=(Graphics2D)gs;
			Font font=new Font("Dialog",Font.PLAIN,20);
		    g.setFont(font);
		    String str="abc";
		    g.drawString(str, 0, 30);
		    FontMetrics fm = g.getFontMetrics();
		    Rectangle2D rec=fm.getStringBounds(str, g);
		    g.drawRect(0, 50, (int)(rec.getWidth()), (int)(rec.getHeight()));
		    
		    g.drawLine(0, 100, 200, 100);
		    
		    String str2="字符串尺寸测试abc";
		    g.drawString(str2, 0, 130);
		    FontMetrics fm2 = g.getFontMetrics();
		    Rectangle2D rec2=fm2.getStringBounds(str2, g);
		    g.drawRect(0, 150, (int)(rec2.getWidth()), (int)(rec2.getHeight()));
		}
	}
  
	
	public static void main(String[] args){
		new StringTest();
	}
}

运行效果:


你可能感兴趣的:(java,String,字符串尺寸)