试图在Java中绘制几个物体



所以我有一个名为"游戏"的类,其中包含我想绘制的对象和计时器的阵列列表。他们都实施了ActionListener。我已经通过ArrayList在游戏循环中进行了操作,并为每个项目调用Action Performperform。然后,每个对象的操作传感方法调用重新涂抹。但是,这似乎只在阵列列表中绘制了最后一个对象。

我在每个对象的Action Perperformed方法中放了一些测试打印,并且该程序确实可以进入所有对象的重新粉刷。

看起来像:

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();
    //...
}

您没有在任何地方触发动作侦听器。您应该添加一行

things.get(i).addActionListener(this);

在适当的地方。看起来这样:

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));
        }
        for (int i = 0; i < things.size(); i++)
        {
            things.get(i).addActionListener(this);
        }
        t.start();
        this.setVisible(true);
    }
    public void actionPerformed (ActionEvent e)
    {
        //repaint your gameobject
    }
}

最新更新