JAVA:图形之利用FontMetrics类居中

 1 //利用FontMetrics类居中
 2 import javax.swing.*;
 3 import java.awt.*;
 4 public class TestCenterMessage extends JFrame{
 5    public TestCenterMessage(){
 6        CenterMessage messagePanel = new CenterMessage();
 7        add(messagePanel);
 8        messagePanel.setBackground(Color.WHITE);
 9        messagePanel.setFont(new Font("Californian FB",Font.BOLD,30));
10     }
11     public static void main(String[] agrs){
12         JFrame frame = new TestCenterMessage();
13         frame.setBounds(200,300,300,150);
14         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
15         frame.setVisible(true);
16     }
17 }
18 
19 class CenterMessage extends JPanel{
20    protected void paintComponent(Graphics g){
21        super.paintComponent(g);
22        
23        //得到当前的font metrics
24        FontMetrics fm = g.getFontMetrics();
25        
26        int stringWidth = fm.stringWidth("Welcome to Java");
27        int stringAscent = fm.getAscent();
28        
29        int xCoordinate = getWidth()/2 - stringWidth/2;
30        int yCoordinate = getHeight()/2 +stringAscent/2;
31        
32        g.drawString("Welcome to Java",xCoordinate,yCoordinate);
33     }
34 }

 

 对比:

仔细观察,字符串稍微偏高

 1 import javax.swing.*;
 2 import java.awt.*;
 3 public class TestCenterMessage extends JFrame{
 4    public TestCenterMessage(){
 5        CenterMessage messagePanel = new CenterMessage();
 6        add(messagePanel);
 7        messagePanel.setBackground(Color.WHITE);
 8        messagePanel.setFont(new Font("Californian FB",Font.BOLD,30));
 9     }
10     public static void main(String[] agrs){
11         JFrame frame = new TestCenterMessage();
12         frame.setBounds(200,300,300,150);
13         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
14         frame.setVisible(true);
15     }
16 }
17 
18 class CenterMessage extends JPanel{
19    protected void paintComponent(Graphics g){
20        super.paintComponent(g);
21        
22        //得到当前的font metrics
23        FontMetrics fm = g.getFontMetrics();
24        
25        int stringWidth = fm.stringWidth("Welcome to Java");
26        int stringAscent = fm.getAscent();
27        
28        int xCoordinate = getWidth()/2 - stringWidth/2;
29        //int yCoordinate = getHeight()/2 +stringAscent/2;
30        int yCoordinate = getHeight()/2;
31 
32        g.drawString("Welcome to Java",xCoordinate,yCoordinate);
33     }
34 }

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值