头等舱
private void spielfenster() {
setSize(1280, 720);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("");
setLayout(null);
setLocationRelativeTo(null);
addKeyListener(new Steuerung());
}
[...]
private void run() {
while(true){
if(we.nachRechts == true && we.mariox < (1280 - 38)){
we.mariox += 4;
repaint();
}
if(we.nachLinks == true && we.mariox > 0){
we.mariox -= 4;
repaint();
}
try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}
}
}
二等
package game;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class Steuerung extends KeyAdapter{
public Werte we = new Werte(); //object, to get access to the global values in class "Werte"
public void keyPressed(KeyEvent p){
int keys = p.getKeyCode();
if(keys == KeyEvent.VK_D){we.nachRechts = true;}
if(keys == KeyEvent.VK_S ){we.nachLinks = true;}
}
public void keyReleased(KeyEvent r){
int key = r.getKeyCode();
if(key == KeyEvent.VK_D){we.nachRechts = true;}
if(key == KeyEvent.VK_S ){we.nachLinks = true;}
}
}
新问题:当我将按键侦听器的确切代码放在“Spielfenster”类中时,它工作正常。问题出在哪里?
第二个问题(机器人现在对我来说不是很重要,但也很高兴知道):如果我在“Steuerung”类中创建一个“Spielfenster”对象,则框架每秒打开自己大约 10 次。?!
感谢之前的!棕榈