简体   繁体   中英

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. However, x and y don't go up, as if the result wasn't recorded. If I increment them before printing results, it is one, showing it increased properly from its original value . If I increment after printing the value, it will show no difference in value. Here is my code:

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();
    };
}

The 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();
    }
}

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. Thank you for your help.

You are creating a new MovingGame in the actionPerformed() method. Instead, you should pass a reference to the game created in your main Method. 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. Try creating the object outside of the actionPerformed method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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