0

我有一些需要在屏幕上绘制的东西,但这需要正确绘制字体指标。我还需要使用 repaint() 或其他东西在屏幕上绘制。

如果我有paintComponent(Graphics)方法,我可以通过g.getFontMetrics(g.getFont()). 问题是,我不能告诉它自己画。它仅在发生某些事情(例如调整组件大小)时才会这样做。

然后,如果我只使用 normal paint(Graphics),我可以repaint()在我想要的时候使用它来绘制,但调用g.getFontMetrics(g.getFont())不会返回正确的值。有任何想法吗?

repaint();//I need to call repaint() or something similar to draw to the screen when I want it to

public void paint(Graphics g){
    FontMetrics metrics = g.getFontMetrics(g.getFont());//Returns different metrics than that of paintComponent(Graphics)
}

public void paintComponent(Graphics g){
    FontMetrics metrics = g.getFontMetrics(g.getFont());//Returns different metrics than that of paint(Graphics)
}
4

1 回答 1

2

问题是,我不能告诉它自己画。

您只需repaint()在组件上使用。repaint() 方法将调用paint(),而paint() 又调用paintComponent()。有关详细信息,请参阅仔细查看绘制机制

我将它设置为变量并使用该字体对象而不是使用 g.getFont()

从上面给出的教程链接中,您将看到您应该覆盖paintComponent() 而不是paint(),所以这不是问题。

于 2014-10-01T13:09:35.847 回答