控件内容的更新主要通过按钮,鼠标,键盘的事件响应来完成。也可循环定时来完成。如实时显示接收的数据的场景下,不需要通过与人的交互就能显示。
此方法比利用动画简单
此代码循环显示变化的数字
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.layout.HBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
public class App extends Application {
static int t;
public void start(Stage primaryStage) throws Exception {
TextArea textArea=new TextArea();
textArea.setPrefSize(720,480);
textArea.setFont(Font.font("Verdana", FontWeight.BLACK,20));
HBox hBox=new HBox();
hBox.getChildren().addAll(textArea);
//------------------------------------------------------------------------------------
Timer timer = new Timer(); //循环定时更新textarea
timer.schedule(new TimerTask() { //javafx UI和事件方法内不能使用Thread.sleep(),也就是App.start()内不能使用。
//所以 另起一线程Ys每秒输入一数字
public void run() {
textArea.setText(String.valueOf(t));
}
}, 100, 100);
//--------------------------------------------------------------------------------------
Scene scene = new Scene(hBox, 720, 480);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) throws InterruptedException, IOException {
Ys ys=new Ys();
ys.start();
launch(args);
}
}
class Ys extends Thread{
public void run(){
for(int n=0;n<1000;n++){
App.t=n;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}