package thinking;
import java.awt.*;
import javax.swing.*;
public class My extends JFrame{
public My(){
CenterMessage cm = new CenterMessage();
add(cm);
cm.setBackground(Color.BLACK);//背景色调
cm.setFont(new Font("Californian FB",Font.BOLD,50));//改变字体大小
}
public static void main(String[] args){
My me = new My();
me.setTitle("ziti");
me.setSize(700,300);
me.setLocationRelativeTo(null);
me.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
me.setVisible(true);
}
}
class CenterMessage extends JPanel{
protected void paintComponent(Graphics g){
super.paintComponent(g);
FontMetrics fm = g.getFontMetrics();
//找到中间位置来展示
int stringWidth = fm.stringWidth("Welcome to ;
int stringAscent = fm.getAscent(); //问题???
int xCoordinate = getWidth()/2 - stringWidth/2;//获得在基线上最左端字体的x坐标位置
int yCoordinate = getHeight()/2 + stringAscent/2;//获得在基线上最左端字体的y坐标位置
g.drawString("Welcome to Java", xCoordinate, yCoordinate);
}
}
存在问题
2.4利用FontMetrics类居中显示
最新推荐文章于 2020-12-19 13:22:46 发布