Java 变量未按计时器更新

Java Variables not updating on timer

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

移动游戏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 class:

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 值保持不变,变化仅显示在方法内部,但仅在特定的 运行 中显示。谢谢你的帮助。

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

您正在 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));