2017-04-08 1 views
0

저는 자바 초보자이고 제 게임을위한 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; 
} 

: 5 초가 아닌 2 초 동안 실행되도록 타이머를 업데이트해야합니다. 분명히, 이것은 작동하지 않습니다.

버튼을 클릭했을 때 타이머의 속도가 변경되도록하려면 어떻게해야합니까? 이 같은

답변

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

관련 문제