2016-05-30 10 views
1

ラベルの値をどのようにリフレッシュすることができますか?JavaFX - リフレッシュラベル

私は、LabelのテキストをStringPropertyにバインドします。ここは大丈夫です。

私はボタンがあり、ボタンを押すごとに、繰り返しのステップごとにラベル値を更新したいと思います。 しかし、私は最後の値だけを見ることができます。どうして?

@FXML 
private Label label; 

@FXML 
private void handleButtonAction(ActionEvent event) throws InterruptedException {  
    for(int i=0;i<1001;i++){ 

     try { 
      Thread.sleep(1); 
     } catch (InterruptedException ie) { 
      //Handle exception 
     }    
     this.value.setValue(i+"");     
    } 
}  

// Bind 
private StringProperty value = new SimpleStringProperty("0"); 

@Override 
public void initialize(URL url, ResourceBundle rb) { 
    // Bind label to value. 
    this.label.textProperty().bind(this.value); 
}  

答えて

0

あなたはThread.sleep(1);呼び出すときさて、あなたは実際のJavaFXアプリケーションスレッド(GUIスレッドを)停止し、したがって、あなたはGUIを更新することを防ぎます。

基本的に必要なのは、実際に一定時間停止したTaskという背景です。その後、再びスリープ状態になる前にPlatform.runLaterを呼び出してJavaFXアプリケーションスレッドのGUIを更新します。

例:

package application; 

import javafx.application.Application; 
import javafx.application.Platform; 
import javafx.beans.property.SimpleStringProperty; 
import javafx.beans.property.StringProperty; 
import javafx.concurrent.Task; 
import javafx.event.ActionEvent; 
import javafx.event.EventHandler; 
import javafx.stage.Stage; 
import javafx.scene.Scene; 
import javafx.scene.control.Button; 
import javafx.scene.control.Label; 
import javafx.scene.layout.HBox; 


public class Main extends Application { 

    private StringProperty value = new SimpleStringProperty("0"); 

    @Override 
    public void start(Stage primaryStage) { 
     try { 
      HBox root = new HBox(); 
      Scene scene = new Scene(root,400,400); 

      Label label = new Label(); 

      Button b1 = new Button("Press Me"); 
      b1.setOnAction(new EventHandler<ActionEvent>() { 

       @Override 
       public void handle(ActionEvent event) { 
        // Background Task 
        Task<Integer> task = new Task<Integer>() { 
         @Override 
         protected Integer call() throws Exception { 
          int i; 
          for (i = 0; i < 1001; i++) { 
           final int val = i; 
           try { 
            Thread.sleep(1); 
           } catch (InterruptedException ie) { 
           } 

           // Update the GUI on the JavaFX Application Thread 
           Platform.runLater(new Runnable() { 

            @Override 
            public void run() { 
             value.setValue(String.valueOf(val)); 
            } 
           }); 

          } 
          return i; 
         } 
        }; 

        Thread th = new Thread(task); 
        th.setDaemon(true); 
        th.start(); 
       } 
      }); 


      label.textProperty().bind(value); 
      root.getChildren().addAll(b1, label); 

      primaryStage.setScene(scene); 
      primaryStage.show(); 
     } catch(Exception e) { 
      e.printStackTrace(); 
     } 
    } 



    public static void main(String[] args) { 
     launch(args); 
    } 
} 

あなたは単に鉱山であなたのボタンの取り扱いを更新する必要があります。