试图用Java绘制几个对象

时间:2018-03-31 00:00:10

标签: java timer actionlistener paintcomponent repaint

所以我有一个名为Game的类,它包含我想要绘制的对象的ArrayList和一个计时器。它们都实现了ActionListener。 我在GameList中通过ArrayList进行了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();
    //...
}

1 个答案:

答案 0 :(得分:0)

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

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
    }
}