JavaFX中的实时更新折线图
我在更新JavaFXUI时遇到了问题-我想在场景已经显示时更新折线图和一些标签。 我的任务是在另一个类中调用函数进行一些计算,该类返回数据系列并将更新的系列添加到图表中 以下循环中的代码可能表示我要执行的操作:JavaFX中的实时更新折线图,java,multithreading,javafx,concurrency,linechart,Java,Multithreading,Javafx,Concurrency,Linechart,我在更新JavaFXUI时遇到了问题-我想在场景已经显示时更新折线图和一些标签。 我的任务是在另一个类中调用函数进行一些计算,该类返回数据系列并将更新的系列添加到图表中 以下循环中的代码可能表示我要执行的操作: //double x - x value of the point i want to add to my chart //double y - y value of the point i want to add to my chart //string s - some resul
//double x - x value of the point i want to add to my chart
//double y - y value of the point i want to add to my chart
//string s - some result from function
mySeries.getData().add(new XYChart.Data(x, y));
someLabel.setText(s);
我的程序冻结,一段时间后只给出最终的解决方案,但我希望在添加点之后,而不是在执行结束时,在图表上看到这些点。如果进程太快,我希望在将下一个点添加到图表之前添加Thread.sleep1000
我知道这与线程、并发性和任务有关,但我还没有找到解决方案。我试图使用我在这里找到的一些代码,但仍然不知道正确答案。每个用户操作,例如单击按钮,都会在UI线程中通知您的操作侦听器。UI线程中的逻辑应该尽可能快。我认为您正在对一个用户事件做出反应,然后在UI线程中执行一个长时间运行的任务。尝试将代码放在后台线程中。此外,您需要将UI更新再次放回UI线程中。您可以使用Platform.runLater执行此操作 大概是这样的:
public class Test extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
Scene scene = new Scene(createChart());
primaryStage.setScene(scene);
primaryStage.setHeight(800);
primaryStage.setWidth(1200);
primaryStage.show();
}
private Parent createChart() {
LineChart<Number, Number> lc = new LineChart<>(new NumberAxis(), new NumberAxis());
XYChart.Series<Number, Number> series = new XYChart.Series<>();
lc.getData().add(series);
new Thread(() -> {
try {
Thread.sleep(5000);
for (int i = 0; i < 15; i++) {
int finalI = i;
Platform.runLater(() -> series.getData().add(new XYChart.Data<>(1 + finalI, 1 + finalI)));
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
return lc;
}
}您在主线程上做了很多工作。