【发布时间】:2018-03-31 00:00:10
【问题描述】:
所以我有一个名为 Game 的类,其中包含我要绘制的对象的 ArrayList 和一个计时器。它们都实现了 ActionListener。 我通过 ArrayList 在 Game 循环中执行 actionPerformed 并为每个项目调用 actionPerformed。然后,每个对象的 actionPerformed 方法调用 repaint。但是,这似乎只绘制了 ArrayList 中的最后一个对象。
我在每个对象的 actionPerformed 方法中放了一些测试打印,程序确实到达了所有对象的重绘线。
它看起来像:
public class Game extends JFrame implements ActionListener
{
public ArrayList<GameObject> things = new ArrayList<GameObject>();
public Timer t = new Timer(5, this);
public Game ()
{
super();
this.setSize(620, 440);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setTitle("Moving Ball");
GameObject b = new Ball(this);
GameObject p = new Paddle(this);
things.add(b);
things.add(p);
for (int i = 0; i < things.size(); i++)
{
this.add(things.get(i));
}
t.start();
this.setVisible(true);
}
public void actionPerformed (ActionEvent e)
{
for (int i = 0; i < things.size(); i++)
{
things.get(i).actionPerformed(e);
}
}
}
并且游戏对象已经覆盖了paintComponent并包含:
public void actionPerformed (ActionEvent e)
{
//...
repaint();
//...
}
【问题讨论】:
标签: java timer actionlistener paintcomponent repaint