Reputation: 691
I want to update a Screen, which i created with a FXML-file.
I though this: Link was the solution, but i dont get the code to run. I found some other parts of code but no one worked for me. I am not shure if i use a different version (see Link) or maybe i am just an idot... but we will see...
I made a very simple exampel to show my problem, so that hopefully someone can show me on this simple example how it works.
JavaFXApplication.java
package javafxapplication;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class JavaFXApplication extends Application {
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
FXMLDocumentController.java
package javafxapplication;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
public class FXMLDocumentController implements Initializable {
@FXML
private Label label;
@Override
public void initialize(URL url, ResourceBundle rb) {
label.setText("This Label was initialized.");
}
public void update(){
label.setText("This Label was updated :)"); //Just4Example... normaly here is some SQL-Stuff...
}
}
FXMLDocument.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml" fx:controller="javafxapplication.FXMLDocumentController">
<children>
<Label layoutX="100" layoutY="100" minHeight="16" minWidth="69" fx:id="label" />
</children>
</AnchorPane>
I want to start the "update"-Methode in the controller every 5 seconds. But when i use a Timer to do this... the Controller is gone. So when the Timer starts the Methode there are no @FXML connections... Maybe the Controller should created manualy... or linke the second linke... but i dont get the code to run... confused... frustrated...
Thank you very much
Upvotes: 1
Views: 4169
Reputation: 49195
Try this
@Override
public void initialize(URL url, ResourceBundle rb) {
label.setText("This Label was initialized.");
Timeline timeline = new Timeline(
new KeyFrame(Duration.seconds(2),
new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
// Call update method for every 2 sec.
update();
}
}));
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
}
However using timeline in SQL query task will block UI JavaFX thread, causing the screen to freeze while querying. So use ScheduledService (introduced in JavaFX 8) instead.
Upvotes: 2