java - 如何在 JButton ActionListener 中调用需要 InterruptedException 的方法

标签 java jbutton actionlistener interrupted-exception

我希望能够按下一个按钮并创建一个使用 Java 2d 的小游戏。 我尝试使用 try/catch 但它陷入无限循环(因为我猜是 create 方法中的 while 循环)

  Button.addActionListener(new ActionListener ()  {
                public void actionPerformed(ActionEvent e)  {

                        game.create();/***is a new window with a small 2d game,
                        the 'create' method requires and InterruptedException to be thrown.***/ 




                }

            });

这是创建方法的代码:

public void create () throws InterruptedException {

    JFrame frame = new JFrame("Mini Tennis");
    GameMain gamemain = new GameMain();
    frame.add(gamemain);
    frame.setSize(350, 400);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    while (true) {
        gamemain.move();
        gamemain.repaint();
        Thread.sleep(10);

    }
}

最佳答案

我相信您的无限循环正在阻止 Swing 线程响应您的按钮。

尝试将循环放在单独的线程中:

public void create () throws InterruptedException {

    JFrame frame = new JFrame("Mini Tennis");
    GameMain gamemain = new GameMain();
    frame.add(gamemain);
    frame.setSize(350, 400);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    (new Thread() {
    public void run() {
        while (true) {
            gamemain.move();
            gamemain.repaint();
            Thread.sleep(10);
        }
    }
    ).start();
}

关于java - 如何在 JButton ActionListener 中调用需要 InterruptedException 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36221934/

相关文章:

java - 如何在 JFrame 中显示不同的组件?

java - 如何在 Maven Java 项目的源文件夹中添加图像?

java - Amazon Cloudwatch Logs - PutLogEvents 请求 - 给定的 sequenceToken 无效

java - 为什么 Vector 会出现 ConcurrentModificationException?

java - keyReleased 函数不恢复 java 中的原始背景颜色

java - JButton 保持焦点时间过长

java - JButton 更改文本字段的文本颜色

java - ActionListener 失败 - Java For-Each 分配给 JMenuItem

java - JList 中的 ActionListener 出现 ArrayIndexOutOfBoundsException

java - 将类的静态变量重新初始化为它们的原始值java