Wednesday 9 May 2018

JavaFX application thread

JavaFX program execution done by JavaFX application thread and not by the main thread. We can confirm the same using below application.

HelloWorld.java
package com.sample.demos;

import static javafx.geometry.Pos.CENTER;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class HelloWorld extends Application {
 @Override
 public void start(Stage primaryStage) {

  String threadName = Thread.currentThread().getName();

  Button button = new Button();
  button.setText("Click Me to know thread details");

  Text message = new Text();

  button.setOnAction(event -> {
   message.setText("Application is getting executed by : " + threadName);
  });

  VBox vBox = new VBox(10, button, message);
  vBox.setAlignment(CENTER);

  Scene scene = new Scene(vBox, 600, 400);

  /* Set the scene to primaryStage, and call the show method */
  primaryStage.setTitle("Hello JavaFX Example");
  primaryStage.setScene(scene);
  primaryStage.show();
 }

}

TestFX.java
package com.sample.demos;

import javafx.application.Application;

public class TestFX {
 public static void main(String args[]) {
  Application.launch(HelloWorld.class, args);
 }
}

When you ran above application, you can able to see below window.


Click on the button to see the thread executing this application.



As you observe above window, the application is getting executed by ‘JavaFX Application Thread’.


Previous                                                 Next                                                 Home

No comments:

Post a Comment