Switching views/fxml on gluon Application - javafx

I am developing a gluon application with JavaFX but i can't understand very well how to switch scene (or view?) by clicking a button.
If i click the button "load from file" in the image below, my code should perform some tasks, and then it should change the view, loading a new fxml, that i've added to the app manager.
Screenshoot
main class that extends Application:
package com.knnapplication;
import com.knnapplication.views.ExampleView;
import com.knnapplication.views.PrimaryView;
import com.knnapplication.views.SecondaryView;
import com.gluonhq.charm.glisten.application.AppManager;
import com.gluonhq.charm.glisten.visual.Swatch;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import static com.gluonhq.charm.glisten.application.AppManager.HOME_VIEW;
public class KNNApplication extends Application {
public static final String PRIMARY_VIEW = HOME_VIEW;
public static final String SECONDARY_VIEW = "Secondary View";
public static final String EXAMPLE_VIEW = "Example View";
private final AppManager appManager = AppManager.initialize(this::postInit);
#Override
public void init() {
appManager.addViewFactory(PRIMARY_VIEW, () -> new PrimaryView().getView());
appManager.addViewFactory(SECONDARY_VIEW, () -> new SecondaryView().getView());
appManager.addViewFactory(EXAMPLE_VIEW, () -> new ExampleView().getView());
DrawerManager.buildDrawer(appManager);
}
#Override
public void start(Stage primaryStage) throws Exception {
appManager.start(primaryStage);
}
private void postInit(Scene scene) {
Swatch.BLUE.assignTo(scene);
scene.getStylesheets().add(KNNApplication.class.getResource("style.css").toExternalForm());
((Stage) scene.getWindow()).getIcons().add(new Image(KNNApplication.class.getResourceAsStream("/icon.png")));
}
public static void main(String args[]) {
launch(args);
}
}
event that handles the button click
#FXML
void LoadFile(ActionEvent event) {
//connection to server
InetAddress addr;
try {
addr = InetAddress.getByName("127.0.0.1");
} catch (UnknownHostException e) {
System.out.println(e.toString());
return;
}
Client c;
try {
c=new Client("127.0.0.1", 2025, label);
/*
HERE I SHOULD SWITCH VIEW
*/
AppManager.getInstance().switchView("EXAMPLE_VIEW");
} catch (IOException e) {
label.setText(e.toString());
System.out.println(e.toString());
return;
} catch (NumberFormatException e) {
label.setText(e.toString());
System.out.println(e.toString());
return;
} catch (ClassNotFoundException e) {
label.setText(e.toString());
System.out.println(e.toString());
return;
}
//label.setText("KNN caricato da file");
}
Searching on the web i've found this kind of method, using this line of code " AppManager.getInstance().switchView("EXAMPLE_VIEW");", but it still not work and i can't understand very well how does it works.
I hope you can help me. Thank you so much!

To load a new view you should make a view object and load the FXML/ the nodes on it. Then you can switch to that view by calling home.getAppManager().switchView("your view here"). like in the following example:
FloatingActionButton fab = new FloatingActionButton(MaterialDesignIcon.ADD.text,
e -> home.getAppManager().switchView(ADDHUB_VIEW));
fab.showOn(your view);
also you need to add this view to the app manager in init in main
appManager.addViewFactory(YOUR_VIEW, () -> new YourView().getView());

Related

How to refresh JavaFX screen twice after sleep?

I am using JavaFX to show images on the screen. My FxScreenController code concept is like:
package my.image.concept;
import java.util.function.Consumer;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import org.springframework.stereotype.Component;
#Component
public class FxScreenController {
private ImageSenderClient imageClient;
#FXML
private ImageView imageView;
private Image image;
public FxScreenController(Image image) {
this.image = image;
}
#FXML
public void initialize(){
final ImageSubscriber imageSubscriber = new ImageSubscriber(image);
imageClient.GetImageFrom().subscribe(imageSubscriber);
}
private static class ImageSubscriber implements Consumer<Image> {
private ImageView imageFile;
public ImageSubscriber(Image newImage) {
this.imageFile.setImage(newImage);
}
#Override
public void accept(Image newImage) {
Platform.runLater(() -> imageFile.setImage(newImage));
}
}
}
I am displaying an image that comes from the Subscriber method.
In order to show image on JavaFX Screen, I am calling Platform.runLater(). The image is shown properly.
I would like to show my previous image back after a 2-seconds pause like this:
#Override
public void accept(Image newImage) {
Platform.runLater(() -> imageFile.setImage(newImage));
try {
Thread.sleep(2000); // Wait for 2 sec before updating back to prev image
} catch (InterruptedException ignored) {
//
}
Platform.runLater(() -> imageFile.setImage(prewImage));
}
However, here it doesn't show my newImage because it doesn't refresh the screen.
How can I can refresh the FX screen before calling Thread.sleep, so that I can show my newImage for 2 seconds on the FX screen?
Creating new Thread solved my problem.
#Override
public void accept(Image newImage) {
Thread timerThread = new Thread(() -> displayImage(newImage));
timerThread.start();
}
private void displayImage(Image newImage) {
Platform.runLater(() ->
imageBg.setImage(newImage)
);
try {
Thread.sleep(2000); // Wait for 2 sec before updating back to main
}
catch (InterruptedException ignored) {
}
imageBg.setImage(prevImage);
}

JavaFx: about quartz scheduler

Hello I have a problem in a routine using quartz scheduler I need to shutdown my Scheduler method:
javafx stop
I can't declare my scheduler out of my stage start:
#Override
public void start(Stage stage) throws Exception {
Scheduler s = StdSchedulerFactory.getDefaultScheduler();
JobDetail j = JobBuilder.newJob(ChecarJob.class).build();
Trigger t = TriggerBuilder.newTrigger().withIdentity("CroneTrigger")
.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(60).repeatForever()).build();
try {
s.start();
try {
s.scheduleJob(j,t);
} catch (Exception e) {
e.printStackTrace();
}
} catch (SchedulerException se) {
se.printStackTrace();
}
Parent root = FXMLLoader.load(getClass().getResource("/fxml/Principal.fxml")); //carrega fxml
Scene scene = new Scene(root); //coloca o fxml em uma cena
stage.setScene(scene); // coloca a cena em uma janela
stage.show(); //abre a janela
setStage(stage);
}
and I need to declare it was outside my start to be able to use shutdown inside stop ()
#Override
public void stop() {
UsuarioDAO u = new UsuarioDAO();
u.setOffiline();
s.shutdown();
Platform.exit();
System.exit(0);
}
if I do that I did above I have an error because my Scheduler was created inside a method and is not global
And the scheduler doesn't allow me to create it at global scope for some reason
my code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package views;
import dao.UsuarioDAO;
import dao.qtdRegistrosDAO;
import rotinas.BackupJob;
import rotinas.ChecarJob;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javax.swing.JOptionPane;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
/**
* FXML Controller class
*
* #author SpiriT
*/
public class Principal extends Application {
private static Stage stage; //uma janela
private static qtdRegistrosDAO aQtdRegistrosDAO;
public Principal() {
}
private void blockMultiInstance() {
try {
ServerSocket serverSocket = new ServerSocket(9581);
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "Software já está aberto!", "Atenção", JOptionPane.WARNING_MESSAGE);
System.exit(0);
}
}
private void backup (){
try {
Scheduler sx = StdSchedulerFactory.getDefaultScheduler();
JobDetail jx = JobBuilder.newJob(BackupJob.class).build();
Trigger tx = TriggerBuilder.newTrigger().withIdentity("CroneTrigger2")
.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(60).repeatForever()).build();
try {
sx.start();
try {
sx.scheduleJob(jx,tx);
} catch (Exception e) {
e.printStackTrace();
}
} catch (SchedulerException se) {
se.printStackTrace();
}
} catch (SchedulerException ex) {
Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void stop() {
UsuarioDAO u = new UsuarioDAO();
u.setOffiline();
s.shutdown();
Platform.exit();
System.exit(0);
}
#Override
public void start(Stage stage) throws Exception {
Scheduler s = StdSchedulerFactory.getDefaultScheduler();
JobDetail j = JobBuilder.newJob(ChecarJob.class).build();
Trigger t = TriggerBuilder.newTrigger().withIdentity("CroneTrigger")
.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(60).repeatForever()).build();
try {
s.start();
try {
s.scheduleJob(j,t);
} catch (Exception e) {
e.printStackTrace();
}
} catch (SchedulerException se) {
se.printStackTrace();
}
Parent root = FXMLLoader.load(getClass().getResource("/fxml/Principal.fxml")); //carrega fxml
Scene scene = new Scene(root); //coloca o fxml em uma cena
stage.setScene(scene); // coloca a cena em uma janela
stage.show(); //abre a janela
setStage(stage);
}
public static Stage getStage() {
return stage;
}
public static void setStage(Stage stage) {
Principal.stage = stage;
}
public static void main(String[] args) {
launch(args);
}
}
If I raise her out of my start stage I can't
Scheduler s = StdSchedulerFactory.getDefaultScheduler();
JobDetail j = JobBuilder.newJob(ChecarJob.class).build();
Trigger t = TriggerBuilder.newTrigger().withIdentity("CroneTrigger"
Define a reference to the scheduler as a member of the Application
class.
Assign the scheduler reference in your start method.
When the application is stopped, call the appropriate method on the scheduler to safely shut it down.
Sample code
public class Principal extends Application {
private Scheduler s;
public void start(Stage stage) throws Exception {
s = StdSchedulerFactory.getDefaultScheduler();
// other work ...
}
public void stop() {
if (s != null) {
// pass true as a parameter if you want to wait
// for scheduled jobs to complete
// (though it will hang UI if you do that on FX thread).
s.shutdown();
}
}
}
There may be other issues with your code (I haven't checked), and I don't know if this answer will solve the core of your problem, but it will allow you to define a Scheduler instance as a reference in your application, which seems to be something you are asking for.

Update label from nested function called from Task API in JavaFX

I am performing some background task using this class
class Download extends Task{
protected Object call() throws Exception {
try {
updateMessage("Establishing Connection");
DownloadHelper downloadHelper = new DownloadHelper();
downloadHelper.performTask();
return null;
} catch (IOException | ParseException ex) {
logger.error(ExceptionUtils.getStackTrace(ex));
throw ex;
}
}
}
This Task in turn calls DownloadHelper to perform some task.
class DownloadHelper{
public DownloadHelper(){
}
public void performTask(){
----
----
}
}
Is there a way to update the status message of the Task API (updateMessage()) from the DownloadHelper class.?
The expedient approach is to pass a reference to the Download task as a parameter to the DownloadHelper constructor. To minimize coupling, you can instead pass a reference to your implementation of updateMessage() as a parameter of type Consumer, "an operation that accepts a single input argument and returns no result."
DownloadHelper helper = new DownloadHelper(this::updateMessage);
Your helper's implementation of performTask() can then ask the updater to accept() messages as needed.
Consumer<String> updater;
public DownloadHelper(Consumer<String> updater) {
this.updater = updater;
}
public void performTask() {
updater.accept("Helper message");
}
A related example is seen here.
import java.util.function.Consumer;
import javafx.application.Application;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
/**
* #see https://stackoverflow.com/q/45708923/230513
*/
public class MessageTest extends Application {
#Override
public void start(Stage primaryStage) {
primaryStage.setTitle("MessageTest");
StackPane root = new StackPane();
Label label = new Label();
root.getChildren().add(label);
Scene scene = new Scene(root, 320, 120);
primaryStage.setScene(scene);
primaryStage.show();
Download task = new Download();
task.messageProperty().addListener((Observable o) -> {
label.setText(task.getMessage());
});
Thread thread = new Thread(task);
thread.setDaemon(true);
thread.start();
}
private static class Download extends Task<String> {
#Override
protected String call() throws Exception {
updateMessage("Establishing connection");
DownloadHelper helper = new DownloadHelper(this::updateMessage);
helper.performTask();
return "MessageTest";
}
#Override
protected void updateMessage(String message) {
super.updateMessage(message);
}
}
private static class DownloadHelper {
Consumer<String> updater;
public DownloadHelper(Consumer<String> updater) {
this.updater = updater;
}
public void performTask() {
updater.accept("Helper message");
}
}
public static void main(String[] args) {
launch(args);
}
}

Multiple independent stages in JavaFX

Is there a way to launch multiple independent stages in JavaFX? By independent I mean that the stages are all created from the main thread.
At the moment my application is more or less an algorithm where I would like to plot some charts and tables during execution (mainly to check whether the results are correct/ to debug).
The problem is that I cannot figure out how to create and show multiple stages independently, i.e. I would like to do something like this
public static void main(){
double[] x = subfunction.dosomething();
PlotUtil.plot(x); //creates a new window and shows some chart/table etc.
double[] y = subfunction.dosomethingelse();
PlotUtil.plot(y); //creates a new window and shows some chart/table etc.
.....
}
which would allow to use PlotUtil as one would use the plotting functions in other scripting languages (like Matlab or R).
So the main question is how to "design" PlotUtils? So far I tried two things
PlotUtils uses Application.launch for each plot call (creating a new stage with a single scene every time) --> does not work as Application.launch can only be invoked once.
Create some kind of "Main Stage" during the first call to PlotUtils, get a reference to the created Application and start subsequent stages from there --> does not work as using Application.launch(SomeClass.class) I am not able to get a reference to the created Application instance.
What kind structure/design would allow me to implement such a PlotUtils function?
Update 1:
I came up with the following idea and was wondering whether there are any major mistakes in this solution.
Interface to be implemented by all "Plots"
public abstract class QPMApplication implements StageCreator {
#Override
public abstract Stage createStage();
}
Plotting functionality:
public class PlotStage {
public static boolean toolkitInialized = false;
public static void plotStage(String title, QPMApplication stageCreator) {
if (!toolkitInialized) {
Thread appThread = new Thread(new Runnable() {
#Override
public void run() {
Application.launch(InitApp.class);
}
});
appThread.start();
}
while (!toolkitInialized) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Platform.runLater(new Runnable() {
#Override
public void run() {
Stage stage = stageCreator.createStage();
stage.show();
}
});
}
public static class InitApp extends Application {
#Override
public void start(final Stage primaryStage) {
toolkitInialized = true;
}
}
}
Using it:
public class PlotStageTest {
public static void main(String[] args) {
QPMApplication qpm1 = new QPMApplication() {
#Override
public Stage createStage() {
Stage stage = new Stage();
StackPane root = new StackPane();
Label label1 = new Label("Label1");
root.getChildren().add(label1);
Scene scene = new Scene(root, 300, 300);
stage.setTitle("First Stage");
stage.setScene(scene);
return stage;
}
};
PlotStage.plotStage(qpm1);
QPMApplication qpm2 = new QPMApplication() {
#Override
public Stage createStage() {
Stage stage = new Stage();
StackPane root = new StackPane();
Label label1 = new Label("Label2");
root.getChildren().add(label1);
Scene scene = new Scene(root, 300, 200);
stage.setTitle("Second Stage");
stage.setScene(scene);
return stage;
}
};
PlotStage.plotStage(qpm2);
System.out.println("Done");
}
}
The easiest approach here would be just to refactor your application so that it is driven from the FX Application thread. For example, you could rewrite your original code block as
public class Main extends Application {
#Override
public void start(Stage primaryStageIgnored) {
double[] x = subfunction.dosomething();
PlotUtil.plot(x); //creates a new window and shows some chart/table etc.
double[] y = subfunction.dosomethingelse();
PlotUtil.plot(y); //creates a new window and shows some chart/table etc.
// .....
}
public static void main(String[] args) {
launch(args);
}
}
Now PlotUtil.plot(...) merely creates a Stage, puts a Scene in it, and show()s it.
This assumes the methods you're calling don't block, but if they do you just have to wrap them in a Task and call PlotUtils.plot(...) in the onSucceeded handler for the task.
If you really want to drive this from a non-JavaFX application, there's a fairly well-known hack to force the JavaFX Application thread to start if it's not already started, by creating a new JFXPanel. A JFXPanel should be created on the AWT event dispatch thread.
Here's a very basic example of the second technique. Start the application and type "show" into the console. (Type "exit" to exit.)
import java.util.Scanner;
import java.util.concurrent.FutureTask;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javax.swing.SwingUtilities;
public class Main {
private JFXPanel jfxPanel ;
public void run() throws Exception {
boolean done = false ;
try (Scanner scanner = new Scanner(System.in)) {
while (! done) {
System.out.println("Waiting for command...");
String command = scanner.nextLine();
System.out.println("Got command: "+command);
switch (command.toLowerCase()) {
case "exit":
done = true;
break ;
case "show":
showWindow();
break;
default:
System.out.println("Unknown command: commands are \"show\" or \"exit\"");
}
}
Platform.exit();
}
}
private void showWindow() throws Exception {
ensureFXApplicationThreadRunning();
Platform.runLater(this::_showWindow);
}
private void _showWindow() {
Stage stage = new Stage();
Button button = new Button("OK");
button.setOnAction(e -> stage.hide());
Scene scene = new Scene(new StackPane(button), 350, 75);
stage.setScene(scene);
stage.show();
stage.toFront();
}
private void ensureFXApplicationThreadRunning() throws Exception {
if (jfxPanel != null) return ;
FutureTask<JFXPanel> fxThreadStarter = new FutureTask<>(() -> {
return new JFXPanel();
});
SwingUtilities.invokeLater(fxThreadStarter);
jfxPanel = fxThreadStarter.get();
}
public static void main(String[] args) throws Exception {
Platform.setImplicitExit(false);
System.out.println("Starting Main....");
new Main().run();
}
}
Here is something more along the lines I would actually follow, if I wanted the user to interact via the OS terminal (i.e. using System.in). This uses the first technique, where the application is driven by an FX Application subclass. Here I create two background threads, one to read commands from System.in, and one to process them, passing them via a BlockingQueue. Even though nothing is displayed in the main FX Application Thread, it is still a very bad idea to block that thread waiting for commands. While the threading adds a small level of complexity, this avoids the "JFXPanel" hack, and doesn't rely on there being an AWT implementation present.
import java.util.Scanner;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class FXDriver extends Application {
BlockingQueue<String> commands ;
ExecutorService exec ;
#Override
public void start(Stage primaryStage) throws Exception {
exec = Executors.newCachedThreadPool(runnable -> {
Thread t = new Thread(runnable);
t.setDaemon(true);
return t ;
});
commands = new LinkedBlockingQueue<>();
Callable<Void> commandReadThread = () -> {
try (Scanner scanner = new Scanner(System.in)) {
while (true) {
System.out.print("Enter command: ");
commands.put(scanner.nextLine());
}
}
};
Callable<Void> commandProcessingThread = () -> {
while (true) {
processCommand(commands.take());
}
};
Platform.setImplicitExit(false);
exec.submit(commandReadThread);
exec.submit(commandProcessingThread);
}
private void processCommand(String command) {
switch (command.toLowerCase()) {
case "exit":
Platform.exit();
break ;
case "show":
Platform.runLater(this::showWindow);
break;
default:
System.out.println("Unknown command: commands are \"show\" or \"exit\"");
}
}
#Override
public void stop() {
exec.shutdown();
}
private void showWindow() {
Stage stage = new Stage();
Button button = new Button("OK");
button.setOnAction(e -> stage.hide());
Scene scene = new Scene(new StackPane(button), 350, 75);
stage.setScene(scene);
stage.show();
stage.toFront();
}
public static void main(String[] args) {
launch(args);
}
}

How to update text box in JavaFX Application after 5 seconds of running?

I have a single controller class "FXController.java" and my FXApplication.java that extends "Application" and contains the launch code. In a separate class "TestFX.java" I call the start method in the "FXApplication.java" that starts the gui. I want to be able to access its controller so that I can change the text within a textfield of the controller. In my FXApplication.java, within the "launch" method I create a variable for the FXLoader and use the "getController" method and set it to a public variable: public FXController theController.
Within the TestFX.java, after I call the "start" method in the main method that launches FXApplication.java in a new runnable, I try to access the controller to change the contents of a single textfield, I get an exception that says controller is null. What is the proper way for me to change the contents of the textfield? I feel that the threading is causing problems.
What I am trying to do in my main method is:
Launch the JavaFX Application/GUI
5 seconds later (sleep), change the text of the text field in FXController.java to "Hello World".
Note that the fxml file loaded/used by FXApplication.java is pointed correctly to the FXController.java. Am wondering if there is some way to access the controller despite having spawned a new runnable for the FX application.
FXApplication.java
public class FXApplication extends Application {
public FXController theController;
public void start() {
Application.launch(FXApplication.class, args);
}
#Override
public void start(Stage stage) throws Exception {
FXMLLoader fxmll = new FXMLLoader(getClass().getResource("fxml_example.fxml"));
Parent root = fxmll.load();
theController = fxmll.getController();
stage.setTitle("FXML Welcome");
stage.setScene(new Scene(root, 300, 275));
stage.show();
}
}
My TestFX.java
public class TestFX {
public static FXApplication fxApp = new FXApplication();
public ExecutorService execs;
public Future<?> fut;
TestFX(ExecutorService execs) {
this.execs = execs;
}
public void start() {
fut = execs.submit(new Runnable() {
#Override
public void run() {
fxApp.start();
}
});
}
public static void main(String[] args) {
ExecutorService execs = Executors.newCachedThreadPool();
TestFX testFx = new TestFX(execs);
testFx.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//fxApp.theController.setTextBoxText("Hello Word");
Platform.runLater(() -> fxApp.theController.setTextBoxText("Hello Word"));
}
Stuff that you want to do like this, you should use the Task class. This does all the heavy lifting for you and all you have to do is set up the code you want to run the FXAT when the task completes. Here's an example, I've left out the controller stuff, because it just clutters up the concepts:
import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class HelloWorld extends Application {
private static Label label;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Hello World!");
label = new Label();
label.setText("Waiting...");
StackPane root = new StackPane();
root.getChildren().add(label);
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.show();
Task<Void> sleeper = new Task<Void>() {
#Override
protected Void call() throws Exception {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
return null;
}
};
sleeper.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
#Override
public void handle(WorkerStateEvent event) {
label.setText("Hello World");
}
});
new Thread(sleeper).start();
}
}
The "sleeper" Task doesn't do anything except sleep, but it's going to sleep on a new thread so the FXAT can keep on responding to screen activity. Then when the sleep finishes, the event handler for the succeed will run on the thread that instantiated the Task, in this case the FXAT.
Your code has two problems.
First, you are calling the static FXMLLoader.load(URL) method, instead of calling load on your FXMLLoader instance. Consequently, the FXMLLoader instance never gets to initialize its controller. You need
FXMLLoader fxmll = new FXMLLoader(getClass().getResource("fxml_example.fxml"));
Parent root = fxmll.load();
The second issue is that you are then changing the text of the text box from a background thread, instead of from the FX Application Thread. (Unless you're handling this in the controller class: you don't show the code for that.) You need
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Platform.runLater(() -> fxApp.theController.setTextBoxText("Hello Word"));
You can also do this with a PauseTransition:
PauseTransition pause = new PauseTransition(Duration.seconds(5));
pause.setOnFinished(event -> fxApp.theController.setTextBoxText("Hello Word"));
pause.play();

Resources