[英]Java Variables not updating on timer
I am trying to create a moving object with incrementing x and y coordinates, by setting up a timer in the movingGame class, firing an actionlistener in a different class which in turn runs a method in the original class, which runs the code to increment the x and y variables, and, for checking the values, prints out x and y. 我正在尝试通过在MovingGame类中设置计时器,在另一个类中触发一个动作侦听器来创建带有递增的x和y坐标的移动对象,该动作侦听器又在原始类中运行一个方法,该方法运行代码以递增x和y变量,并且为了检查值,打印出x和y。 However, x and y don't go up, as if the result wasn't recorded. 但是,x和y不会上升,就好像没有记录结果一样。 If I increment them before printing results, it is one, showing it increased properly from its original value . 如果在打印结果之前增加它们,则该值为1,表明它已从其原始值适当增加。 If I increment after printing the value, it will show no difference in value. 如果在打印值后增加数值,则不会显示出任何差异。 Here is my code: 这是我的代码:
movingGame class: 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();
};
}
The ActionPerformer class: 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();
}
}
In summary my problem is that after running the method, the x and y values remain unchanged, and changes are only shown inside the method, but only in the particular run. 总之,我的问题是,运行方法后,x和y值保持不变,并且更改仅在方法内部显示,而仅在特定运行中显示。 Thank you for your help. 谢谢您的帮助。
You are creating a new MovingGame in the actionPerformed()
method. 您正在actionPerformed()
方法中创建一个新的MovingGame。 Instead, you should pass a reference to the game created in your main
Method. 相反,您应该传递对在main
方法中创建的游戏的引用。 Something along the lines 沿线的东西
public class ActionPerformer implements ActionListener {
private movingGame game;
public ActionPerformer(movingGame mg) {
this.game = mg;
}
@Override
public void actionPerformed(ActionEvent e) {
this.game.timeToDraw();
}
}
and then 接着
Timer timer = new Timer(100, new ActionPerformer(this));
You are creating a new MovingGame
object every time an action is performed. 每次执行动作时,您都在创建一个新的MovingGame
对象。 Try creating the object outside of the actionPerformed
method 尝试在actionPerformed
方法之外创建对象
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.