在构造函数中实现ActionListener方法的Java
我试图调用我在构造器中创建(覆盖)的按键方法来允许对象移动。我在主类中实现了ActionListener和KeyListener 这可能吗?我尝试通过在构造函数中实现ActionListener方法的Java,java,swing,actionlistener,keylistener,Java,Swing,Actionlistener,Keylistener,我试图调用我在构造器中创建(覆盖)的按键方法来允许对象移动。我在主类中实现了ActionListener和KeyListener 这可能吗?我尝试通过this.keyPressed(KeyEvent e)调用该方法,但我不知道如何初始化e 做这样的事情最好的方法是什么 Timer timer = new Timer(DELAY, this); public Game(Main game) { this.game = game; gamePanel = new GamePanel
this.keyPressed(KeyEvent e)
调用该方法,但我不知道如何初始化e
做这样的事情最好的方法是什么
Timer timer = new Timer(DELAY, this);
public Game(Main game) {
this.game = game;
gamePanel = new GamePanel();
buttonPanel = new JPanel();
buttonPanel.add(startButton);
this.addKeyListener(this);
this.setFocusable(true);
this.setFocusTraversalKeysEnabled(false);
this.getContentPane().add(gamePanel, BorderLayout.CENTER);
this.getContentPane().add(buttonPanel, BorderLayout.PAGE_END);
this.setSize(1000, 1000);
this.setVisible(true);
}
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
game.move("u");
break;
case KeyEvent.VK_DOWN:
game.move("d");
break;
case KeyEvent.VK_RIGHT:
game.move("r");
break;
case KeyEvent.VK_LEFT:
game.move("l");
break;
}
}
@Override
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();
if (src == timer) {
game.updateBoard();
if (game.gameEnded()) {
timer.stop();
}
repaint();
} else if (src == startButton) {
if (timer.isRunning()) {
timer.stop();
} else {
timer.stop();
}
}
}
问题在于:
while(!game.gameEnded()) {
game.updateBoard();
KeyEvent e = null;
this.keyPressed(e);
}
如果使用Swing事件调度线程调用构造函数,它将阻止它,因此无法调度任何事件
正确的方法应该是使用javax.swing.Timer
,它定期触发ActionEvent
int period = 1000;//fire ActionEvent every second
Timer timer = new Timer(period,new ActionListener(){
public void actionPerformed(ActionEvent e){
//do your stuff, for example
game.updateBoard();
}
});
timer.start();
您不应该自己调用EventListener中的方法,因为它们都应该由事件调度线程处理。谢谢@Judger,这很有帮助。我应该在创建计时器后自动启动它吗?我正在重写
actionPerformed(ActionEvent e)。
我在类的开头全局创建了一个计时器timer timer=new timer(DELAY,this)代码>我在我的actionPerformed(ActionEvent e)
方法objectsrc=e.getSource()的第一行中也调用了这个函数代码>我刚刚编辑了带有更改的问题。类似这样的工作吗?我不认为您可以使用this
作为一个参数来实例化Timer
对象。您应该在构造函数中初始化它。