为什么setFont在写这样的时候不工作?我想绘制消息(字体粗体,大小为20),并在其下面绘制一个带有小蓝色数字的乘法表。
//this is a separate class
public class Start {
public static void main(String[] args){
GUI gui = new GUI();
}
}
public class GUI extends JFrame{
public GUI(){
add(new DrawTable());
setTitle("Multiplication table");
setSize(240, 280);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setResizable(false);
}
}
class DrawTable extends JPanel{
public void paintComponent(Graphics g){
super.paintComponent(g);
this.setBackground(Color.WHITE);
g.setColor(Color.BLUE);
g.setFont(new Font("Times", Font.PLAIN, 11));
for(int i = 1, j = 110; i < 10; i++, j += 15){
g.drawString("" + i, 20, j);
}
for(int i = 1, j = 50; i < 10; i++, j += 20){
g.drawString("" + i, j, 80);
}
for(int i = 1, j = 110; i < 10; i++, j += 15){
for(int k = 1, l = 50; k < 10 ; k++, l += 20){
if((i * k) < 10){
g.drawString("" + i *k , l, j);
}else{
g.drawString("" + i * k, l - 6, j);
}
}
}
//those are the lines im talking about
setFont(new Font("font1", Font.BOLD, 20));
FontMetrics fm = g.getFontMetrics();
int x = (getWidth() / 2) - (fm.stringWidth("Multiplication table"))/2;
g.drawString("Multiplication table", x, 50);
}
}
这只有在我将这四行放在super.paintComponent(g)下时才有效 消息是黑色,粗体和20和数字小和蓝色,但如果我把4 像这里的线条,它的所有小和蓝色,为什么?
答案 0 :(得分:3)
您没有在评论下的图形变量g上调用setFont(...)
。要使字体起作用,它应该是:
g.setFont(...);
即改变
setFont(new Font("font1", Font.BOLD, 20));
FontMetrics fm = g.getFontMetrics();
int x = (getWidth() / 2) - (fm.stringWidth("Multiplication table"))/2;
g.drawString("Multiplication table", x, 50);
为:
g.setFont(new Font("font1", Font.BOLD, 20));
FontMetrics fm = g.getFontMetrics();
int x = (getWidth() / 2) - (fm.stringWidth("Multiplication table"))/2;
g.drawString("Multiplication table", x, 50);
答案 1 :(得分:1)
试试这个:
g.setFont(new Font("//Font name", 1, 20));
1是您想要的样式(您可以尝试任意多种样式,直到找到您喜欢的样式),20是字体大小。