簡體   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