Java变量不在计时器上更新

时间:2017-01-09 20:56:33

标签: java actionlistener

我试图通过在movingGame类中设置一个计时器来创建一个增加x和y坐标的移动对象,在另一个类中触发一个actionlistener,然后在原始类中运行一个方法,该方法运行代码增加x和y变量,并且,为了检查值,打印出x和y。但是,x和y不会上升,就好像结果没有记录一样。如果我在打印结果之前递增它们,它就是一个,显示它从原始值正确增加。如果我在打印值后递增,它将显示没有值的差异。这是我的代码:

movingGame class:

import javax.swing.JFrame;
import javax.swing.Timer;

public class movingGame extends JFrame {

    public int x;
    public int y;

    void moving() {
        Timer timer = new Timer(100,new ActionPerformer());
        timer.start(); 
    }

    public void timeToDraw() {
        //This is where it is supposed to increment.
        x++;
        y++;
        System.out.println("y: "+y);
        System.out.println("x: "+x);
        //If I put x++ and y++ here, it would give a value of 0.
    };

    public static void main(String[] args){
        movingGame d = new movingGame();
        d.setVisible(true);
        d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        d.setSize(1000, 666);
        d.setExtendedState(MAXIMIZED_BOTH); 
        d.moving();
    };
}

ActionPerformer类:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ActionPerformer implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        movingGame m = new movingGame();
        m.timeToDraw();
    }
}

总之,我的问题是在运行方法之后,x和y值保持不变,并且更改仅显示在方法内部,但仅在特定运行中显示。谢谢你的帮助。

2 个答案:

答案 0 :(得分:2)

您正在使用actionPerformed()方法创建新的MovingGame。相反,您应该传递对main方法中创建的游戏的引用。一些事情

public class ActionPerformer implements ActionListener {
    private movingGame game;

    public ActionPerformer(movingGame mg) {
        this.game = mg;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        this.game.timeToDraw();
    }
}

然后

Timer timer = new Timer(100, new ActionPerformer(this));

答案 1 :(得分:0)

每次执行操作时,您都在创建一个新的MovingGame对象。尝试在actionPerformed方法

之外创建对象