【问题标题】:How do i call a method that requires an InterrupedException in a JButton ActionListner如何在 JButton ActionListener 中调用需要 InterruptedException 的方法
【发布时间】:2016-03-25 14:33:09
【问题描述】:

我希望能够按下一个按钮并创建一个使用 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.***/ 




                }

            });

这里是 create 方法的代码:

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);

    }
}

【问题讨论】:

    标签: java jbutton actionlistener interrupted-exception


    【解决方案1】:

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

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

    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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-01
      • 1970-01-01
      • 2013-08-03
      • 1970-01-01
      • 2023-02-02
      • 1970-01-01
      相关资源
      最近更新 更多