gpt4 book ai didi

java - JavaFX 中的实时更新折线图

转载 作者:行者123 更新时间:2023-12-02 13:09:03 25 4
gpt4 key购买 nike

我在更新 JavaFX UI 时遇到问题 - 我想在场景已显示时更新折线图和一些标签。我的任务是进行一些计算(调用其他类中返回数据系列的函数)并将更新的系列添加到图表中。

以下代码(在循环中)可能会呈现我想要做的事情:

//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.sleep(1000)。

我知道这与线程、并发和任务有关,但我还没有找到解决方案。我尝试使用在这里找到的一些代码,但我仍然不知道正确的答案。

最佳答案

每个用户操作,例如单击按钮,将通知 UI 线程内的操作监听器。 UI 线程中的逻辑应该尽可能快。我认为您正在对用户事件使用react,然后在 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;
}

}

关于java - JavaFX 中的实时更新折线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44036735/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com