被卡在使用Java Swing定时器上。

huangapple go评论75阅读模式
英文:

Stuck on using Java Swing Timer

问题

我已经在一个 JFrame 上的画布中创建了一个小矩形。我已经将这个类设为了单例模式(我知道有些人会说这不是一个好的做法,但我对此感到满意)。目前我只是在按下箭头键时使用 repaint() 方法。然而,我现在正在考虑使用 Swing 定时器来创建一个游戏循环。

我已经创建了一个名为 "GameLoop.java" 的类,并添加了以下代码。

public class GameLoop implements ActionListener {

    Timer timer = new Timer(10, this);

    public void actionPerformed(ActionEvent e) {
        timer.start();
        GameCanvas.getInstance().repaint();
    }
}

然而,当按下箭头键时,这并没有对屏幕产生任何影响。我是不是漏掉了什么东西/做错了什么?

英文:

I have created a small rectangle in a canvas which is on a JFrame. I have made the class a singleton (I know some of you will say it's bad practice, but i'm fine with that). I am currently just using the repaint() method whenever an arrow key is pressed. However, I am now looking at making a Game loop with a swing timer.

I have created a class called "GameLoop.java" and added the following code.

public class GameLoop implements ActionListener {

	
	Timer timer = new Timer(10, this);
	
	public void actionPerformed(ActionEvent e) {
		
		timer.start();
		GameCanvas.getInstance().repaint();
		
	}
}

This however, does nothing to the screen when an arrow is pressed. Is there something I am missing / doing wrong?

答案1

得分: 1

"actionPerformed(ActionEvent e)" 只有在计时器启动后才会被调用,因此它不能用于启动计时器。<br/>
你需要在其他地方启动它。例如:

public class GameLoop implements ActionListener {

    GameLoop() {
        Timer timer = new Timer(10, this);
        timer.start();
    }

    public void actionPerformed(ActionEvent e) {
        GameCanvas.getInstance().repaint();
    }
}
英文:

The actionPerformed(ActionEvent e) is called only after the timer starts, so it can not be used to start the timer.<br/>
You need to start it elsewhere. For example:

public class GameLoop implements ActionListener {

    GameLoop() {
    	Timer timer = new Timer(10, this);
        timer.start();
	}

    public void actionPerformed(ActionEvent e) {
        GameCanvas.getInstance().repaint();
    }
}

huangapple
  • 本文由 发表于 2020年4月9日 07:43:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/61111763.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定