如何在Java中初始化图形?
我有一些这样的代码:
public void paintComponent(Graphics graphics){
graphics.setColor(Color.WHITE);
for (GameObject object : GameArea.objects){
graphics.fillRect(object.position.x, object.position.y,object.width, object.height);
}
graphics.setColor(Color.BLUE);
graphics.fillRect(GameArea.square.position.x,GameArea.square.position.y,GameArea.square.width, GameArea.square.height);
for(GameObject object2 : GameArea.objects){
graphics.fillRect(object2.position.x, object2.position.y,object2.width, object.height);
}
}
它位于一个名为FieldPanel的类中。我在MainGame类中这样称呼它:
Timer t = new Timer(50, new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
//The following line does not work:
fieldPanel.paintComponent(Graphics g);
}
});
然而,不起作用的线路给我带来了问题。如何创建新的图形对象以传递到其他类的方法中?还有,当我创建它时,它应该具有什么属性等?我不完全确定Graphics类做什么,解释一下会有帮助
# 1 楼答案
自动调用
paintComponent(Graphics g)
方法。你哪儿都不能叫它。但是如果你想画新的图形,你可以在fieldPanel中使用repaint()
方法在
fieldPanel
在
MainGame
# 2 楼答案
可以使用双缓冲。把它放在你的课堂上
用这个gf画画。 使用计时器重新绘制JComponent
并重写paintComponent()方法,就像您的第一个代码列表一样:
对不起,如果我在田野里弄错了。我记不得了