【问题标题】:Java Implementing ActionListener methods in ConstructorJava 在构造函数中实现 ActionListener 方法
【发布时间】:2017-12-07 00:44:36
【问题描述】:

我试图调用我在构造函数中为我正在制作的游戏创建(覆盖)的 keyPressed 方法以允许对象移动。我在主类中实现了 ActionListener 和 KeyListener。

这甚至可能吗?我尝试通过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();
        }
    }
}

【问题讨论】:

    标签: java swing actionlistener keylistener


    【解决方案1】:

    问题出在这里:

    while(!game.gameEnded()) {
        game.updateBoard();
        KeyEvent e = null;
        this.keyPressed(e);
    }
    

    如果使用 Swing Event-Dispatching-Thread 调用构造函数,它会阻塞它,因此无法调度任何事件。

    正确的方法应该是使用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 中的方法,因为它们都应该由 Event-Dispatching-Thread 处理。

    【讨论】:

    • 感谢@Judger 很有帮助。我应该在创建计时器后自动启动它吗?我正在覆盖actionPerformed(ActionEvent e). 我在类Timer timer = new Timer(DELAY, this); 的开头全局创建了一个计时器我也在我的actionPerformed(ActionEvent e) 方法Object src = e.getSource(); 的第一行调用它
    • 我刚刚编辑了带有更改的问题。这样的东西有用吗?
    • 我认为你不能像这样使用this 作为一个参数来实例化你的Timer 对象。你应该在构造函数中初始化它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多