본문 바로가기

JavaFX

[JavFX] 자바FX Platform runLater 쓰레드 UI 변경

JavaFX에서는 Thread에서 JavaFX UI를 변경하거나, Popup창을 띄워서 UI를 변경하려 할때 에러가 발생한다.

이런 에러를 막기 위해서 사용하면 좋은게 Platform 이다.

 

Platform을 사용해서 fxml 화면이 onload 되면 실행할 수 있다.

 

사용 방식은 간단하다.

직접 Runnable 객체를 생성하는 경우

Platform.runLater(new Runnable(){
  @Override
  public void run(){
    try {
      FXMLLoader loader = new FXMLLoader();
      loader.setLocation(getClass().getClassloader().getResource("path"));
      Parent root = (Parent) loader.load();
      Scene scene = new Scene(root);

      Stage stage = new Stage();
      stage.setScene(scene);
      stage.show();
    catch(Exception e){
    
    }
  }
});

 

 

람다식을 사용하는 경우

 

Platform.runLater(() -> {
	// ...
});

 

 

TableView에서 스크롤을 상단, 하단으로 이동하는 것도 Platform을 사용한다.

scrollTo 안에 0이면 row 0번째로, 마지막이면 row의 마지막 라인을 넣어준다.

 

Platform.runlater( () -> table.scrollTo(0));