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 }