为什么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
像这里一样排成一行,全部都是蓝色,为什么呢?

最佳答案

您不会在注释下的Graphics变量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);

关于java - setFont不能按此顺序工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21003128/

10-10 10:11