package 字体;
import java.awt.*;
import java.awt.font.*;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.*;
import javax.swing.*;
public class FontTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO 自动生成方法存根
FontFrame fr = new FontFrame();
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fr.setVisible(true);
}
}
class FontFrame extends JFrame{
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
public FontFrame(){
setTitle("朱雪珂的世界!!");
setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
FontPanel f = new FontPanel();
add(f);
}
}
class FontPanel extends JPanel{
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
String message = "Hello,World";
Font f = new Font("Serif",Font.BOLD,36);
g2.setFont(f);//将此图形上下文的字体设置为指定字体。
//FontRenderContext 类是正确测量文本所需的信息容器
FontRenderContext context = g2.getFontRenderContext();//此方法将返回一个FontRenderContext 的对象
Rectangle2D bounds = f.getStringBounds(message, context);// 返回指定 FontRenderContext 中指定 String 的逻辑边界。
double x = (getWidth()-bounds.getWidth())/2;
double y = (getHeight()-bounds.getHeight())/2;
double ascent = -bounds.getX();
double baseY = y + ascent;
g2.drawString(message, (int)x, (int)baseY);
g2.setPaint(Color.GRAY);
g2.draw(new Line2D.Double(x,baseY,x+bounds.getWidth(),baseY));
Rectangle2D rect = new Rectangle2D.Double(x,y,bounds.getWidth(),bounds.getHeight());
g2.draw(rect);
}
}