JButtonaを押したときだけ戻るメソッドを作る必要があります。カスタムJButtonクラスがあります
public class MyButton extends JButton {
   public void waitForPress() {
       //returns only when user presses this button
   }
}
と実装したいですwaitForPress。基本的に、メソッドは、ユーザーがマウスでボタンを押したときにのみ戻る必要があります。JTextField私は(ユーザーがを押したときにのみ戻るために)同様の動作を達成しましたSpace:
public void waitForTriggerKey() {
        final CountDownLatch latch = new CountDownLatch(1);
            KeyEventDispatcher dispatcher = new KeyEventDispatcher() {
                public boolean dispatchKeyEvent(KeyEvent e) {
                    if (e.getID() == KeyEvent.KEY_PRESSED && e.getKeyCode() == KeyEvent.VK_SPACE) {
                        System.out.println("presed!");
                        latch.countDown();
                    }
                    return false;
                }
            };
            KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(dispatcher);
            try {
                //current thread waits here until countDown() is called (see a few lines above)
                latch.await();
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }  
            KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher(dispatcher);
    }
しかし、私は同じことをしたいと思いJButtonます。
事前に:actionPerformedこれは良い考えではなく、単にイベントをJButtonから何らかのアクションを実行する必要があるとコメントしたい場合は、ここで尋ねます。私が尋ねたことだけを手伝ってください。ありがとう!!
事前に: actionPerformedを実装しても、問題が直接解決されないことにも注意してください。ボタンを押さなくてもコードが進行するからです。プログラムを停止し、ボタンが押されたときにのみ戻る必要があります。actionPerformedを使用した場合のひどい解決策は次のとおりです。
public class MyButton extends JButton implements ActionPerformed {
   private boolean keepGoing = true;
   public MyButton(String s) {
       super(s);
       addActionListener(this);
   }
   public void waitForPress() {
       while(keepGoing);
       return;
   }
   public void actionPerformed(ActionEvent e) {
       keepGoing = false;
   }
}