我正在尝试通过在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));