JAVA字体设置

 

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);
  
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值