2011-11-14 19 views
0

私は停止ボタンを探していますが、私のコードに当てはまるものは何も見つかりません。Forループ内の停止ボタン

if (O1.isSelected()) { 
    for (int nu = Num; nu > 0; nu--) { 
     try { 
      Robot robot = new Robot(); 
      robot.delay(Num2 * 1000); 
      robot.keyPress(KeyEvent.VK_H); 
      robot.keyPress(KeyEvent.VK_E); 
      robot.keyPress(KeyEvent.VK_L); 
      robot.keyPress(KeyEvent.VK_L); 
      robot.keyPress(KeyEvent.VK_O); 
      robot.keyPress(KeyEvent.VK_SPACE); 
      robot.keyPress(KeyEvent.VK_W); 
      robot.keyPress(KeyEvent.VK_O); 
      robot.keyPress(KeyEvent.VK_R); 
      robot.keyPress(KeyEvent.VK_L); 
      robot.keyPress(KeyEvent.VK_D); 
      robot.keyPress(KeyEvent.VK_ENTER); 
     } catch (AWTException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

私はjbuttonを中断させることを考えていました。 forループ内でjButtonActionPerformedを使用することはできません。どんな援助も大いにあふれている。

ありがとうございました。

+2

作成ループ外のjButtonActionPerformedイベントを使用してグローバル変数を設定した後、その変数の値をチェックするためにループ内に条件を追加します。 – Polynomial

答えて

0

ボタンのクリックハンドラは、それがキャンセルする安全な場所にある場合、そのフィールドのためのあなたのforループチェックを行い、その後、アクションが「停止」されたことを示すためにプライベートフィールドを設定してください:

for (int nu = Num; nu > 0; nu--) { 
    try { 
     Robot robot = new Robot(); 
     robot.delay(Num2 * 1000); 
     if (this.stopRequested) { 
      this.stopRequested = !this.stopRequested; 
      break; 
     } 
     robot.keyPress(KeyEvent.VK_H); 
     robot.keyPress(KeyEvent.VK_E); 
     robot.keyPress(KeyEvent.VK_L); 
     robot.keyPress(KeyEvent.VK_L); 
     robot.keyPress(KeyEvent.VK_O); 
     robot.keyPress(KeyEvent.VK_SPACE); 
     robot.keyPress(KeyEvent.VK_W); 
     robot.keyPress(KeyEvent.VK_O); 
     robot.keyPress(KeyEvent.VK_R); 
     robot.keyPress(KeyEvent.VK_L); 
     robot.keyPress(KeyEvent.VK_D); 
     robot.keyPress(KeyEvent.VK_ENTER); 
    } catch (AWTException e) { 
     e.printStackTrace(); 
    } 
} 
+1

この場合、stopRequested変数は「volatile」と宣言する必要があります – jjmontes

+0

私はあなたが言っていることを完全に理解していません。 –

+0

@NickHaughton:あなたはどのような面を理解していませんか? – StriplingWarrior

関連する問題