按下2个KeyEvent时线程停止

时间:2014-05-20 14:58:42

标签: java multithreading user-interface

我正在用java编写一个蛇游戏,并且轮流由键盘控制。一切正常,但是当我错误地按下2键然后整个应用程序冻结(gui)蛇停止移动,但线程继续根据我的日食运行,我认为这可能是导致问题的默认情况,但声明确实不打印。

private class KeyboardListener extends KeyAdapter {

    public void keyPressed(KeyEvent e) {
        Directions direc = c.getDirectionSnake();
        switch (e.getKeyCode()) {
        case KeyEvent.VK_RIGHT:
        case KeyEvent.VK_NUMPAD6:
            // if it's not the opposite direction
            if (c.getDirectionSnake() != Directions.LEFT)
                c.setDirectionSnake(Directions.RIGHT);
            break;
        case KeyEvent.VK_UP:
        case KeyEvent.VK_NUMPAD8:
            if (c.getDirectionSnake() != Directions.BOTTOM)
                c.setDirectionSnake(Directions.TOP);
            break;

        case KeyEvent.VK_LEFT:
        case KeyEvent.VK_NUMPAD4:
            if (c.getDirectionSnake() != Directions.RIGHT)
                c.setDirectionSnake(Directions.LEFT);
            break;

        case KeyEvent.VK_DOWN:
        case KeyEvent.VK_NUMPAD2:
            if (c.getDirectionSnake() != Directions.TOP)
                c.setDirectionSnake(Directions.BOTTOM);
            break;
        default:
        System.out.println("here");
            break;
        }
    }
}

的JFrame

public Window() throws FileNotFoundException {

    this.setTitle("Snake");
    this.setSize(400, 450);
    this.setVisible(true);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLocationRelativeTo(null);

    gamePanel = new GamePanel();
    topPanel = new TopPanel();

    this.add(new TopPanel(), BorderLayout.NORTH);

    this.add(gamePanel, BorderLayout.CENTER);
    c = new ThreadsController(gamePanel.getSnakeDepartPosition());
    c.start();
    this.buttonPanel = new ButtonPanel(this, c);
    this.add(buttonPanel, BorderLayout.SOUTH);
    this.setVisible(true);

    this.addKeyListener(new KeyboardListener());

}

0 个答案:

没有答案