2017-04-08 54 views
0

我是Java初學者,在我的遊戲JavaFX控制器中,我有以下代碼片段。這是一個按鈕,啓動一個計時器,做一些事情,每5秒,它工作完全正常:用戶單擊按鈕時,如何更改定時器的KeyFrame持續時間?

double seconds = 5.0; 
@FXML 
void unlockBtn(ActionEvent event) { 
      Timeline timer = new Timeline(new KeyFrame(Duration.seconds(seconds), new EventHandler<ActionEvent>() { 

       @Override 
       public void handle(ActionEvent event) { 
        System.out.println("this is called every"+seconds+"seconds on UI thread"); 
       } 
      })); 
      timer.setCycleCount(Timeline.INDEFINITE); 
      timer.play(); 
} 

然後我也有一個按鈕,改變「秒」變量,它的代碼如下所示:

@FXML 
void upgradeSecondsBtn(ActionEvent event) { 
       seconds = 2.0; 
} 

它應該做什麼:它應該更新計時器,以便它現在執行的所有事情都是2秒而不是5秒。顯然,這是行不通的。

如何使它改變點擊按鈕時定時器的速率?

回答

0

像這樣的東西應該工作

Timeline timer; 

@FXML 
void unlockBtn(ActionEvent event) { 
    createTimer(5.0); 
} 

private void createTimer(double seconds) { 
    if (timer != null) { 
     timer.stop(); 
    } 
    timer = new Timeline(new KeyFrame(Duration.seconds(seconds), new EventHandler<ActionEvent>() { 
     @Override 
     public void handle(ActionEvent event) { 
      System.out.println("this is called every"+seconds+"seconds on UI thread"); 
     } 
    })); 
    timer.setCycleCount(Timeline.INDEFINITE); 
    timer.play(); 
} 

@FXML 
void upgradeSecondsBtn(ActionEvent event) { 
    createTimer(2.0); 
} 
+0

是的,它工作得很好。謝謝你的幫助! – 4242