In my JavaFX application, I would like to display live data from a background thread. Does anyone know how to update a linechart from a background thread? Thank you. Below some sample code.
TM
Sample controller
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.chart.LineChart;
import javafx.scene.control.Button;
public class SampleController {
@FXML
Button btnStart;
@FXML
Button btnStop;
@FXML
LineChart myChart;
Process process;
@FXML
public void initialize() {
process = new Process();
}
public void start(ActionEvent event) {
process.start();
}
public void stop(ActionEvent event) {
process.stop();
}
}
Process class. Launches the thread.
public class Process {
private Task task = new Task();
public void start(){
task.start();
}
public void stop(){
task.kill();
}
}
Task class. The thread class which executes the tasks
public class Task extends Thread {
private boolean isActive = true;
@Override
public void run() {
while (isActive) {
try {
// Simulate heavy processing stuff
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Add a new number to the linechart
// Remove first number of linechart
}
}
public void kill(){
isActive = false;
}
}
Main class
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Hello World");
primaryStage.setScene(new Scene(root, 500, 500));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
sample.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.chart.CategoryAxis?>
<?import javafx.scene.chart.LineChart?>
<?import javafx.scene.chart.NumberAxis?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.VBox?>
<VBox maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity"
minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0"
xmlns="http://javafx.com/javafx/10.0.1"
xmlns:fx="http://javafx.com/fxml/1"
fx:controller="sample.SampleController">
<children>
<Button fx:id="btnStart" mnemonicParsing="false" onAction="#start" text="Start" />
<LineChart fx:id="myChart">
<xAxis>
<CategoryAxis side="BOTTOM" />
</xAxis>
<yAxis>
<NumberAxis side="LEFT" />
</yAxis>
</LineChart>
<Button fx:id="btnStop" mnemonicParsing="false" onAction="#stop"
text="Stop" />
</children>
</VBox>