2016-03-25 8 views
1

ボタンを押してJava 2dを使用する小さなゲームを作成したいと考えています。JButton ActionListnerでInterrupedExceptionを必要とするメソッドを呼び出すにはどうすればいいですか?

:createメソッドからのコードがある 私はのtry/catchを使用しようとしましたが、それはここで

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.***/ 




       } 

      }); 

(ので、私は推測する作成方法でwhileループの)無限ループで立ち往生

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

    } 
} 

答えて

2

あなたの無限ループが、スイングスレッドがあなたのボタンに反応しないようにしていると思います。

は別のスレッドで、あなたのループを持ってみてください。完全に働いた

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

いや、あなたに感謝します! – tamalon

+0

私はお手伝いします! –