繁体   English   中英

Java变量未在计时器上更新

[英]Java Variables not updating on timer

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

movingGame类:

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值保持不变,并且更改仅在方法内部显示,而仅在特定运行中显示。 谢谢您的帮助。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM