gpt4 book ai didi

JavaFX 阻止非 UI 线程,直到 GUI 完成更新(暂停转换中)

转载 作者:太空宇宙 更新时间:2023-11-04 09:24:38 26 4
gpt4 key购买 nike

我想可视化我的堆排序。基本上,当我交换数组中的两个元素时,我还想更改代表数组值的图表条形。参见下图。

我在每次数组交换后使用 PauseTransition,因为我想在 GUI 中可视化每个单独的交换,但是,完整的算法在第一个暂停转换的延迟结束之前完成,因此并不是每个步骤都显示在 GUI 上,而仅显示最终结果。

我需要阻止非 UI 线程,以便显示每个交换。

我已经尝试过
Thread.sleep(1000)

But the GUI is hidden until the array is sorted

这是我的 swapElements 代码片段

private void swapElements(int parentIndex, int childIndex) {
int tempParent = array[parentIndex];
array[parentIndex] = array[childIndex];
array[childIndex] = tempParent;


PauseTransition wait = new PauseTransition(Duration.seconds(1));

wait.setOnFinished((e) -> {
Bar parentBar = Controller.bars.get(parentIndex);
Controller.bars.set(parentIndex, Controller.bars.get(childIndex));
Controller.bars.set(childIndex, parentBar);
});
wait.play();
}

这是我的 Controller :

public class Controller implements Initializable {
public HBox hBox;
public static ObservableList<Bar> bars = FXCollections.observableArrayList();


@Override
public void initialize(URL location, ResourceBundle resources) {

bars.addListener(new ListChangeListener<Bar>() {
@Override
public void onChanged(Change<? extends Bar> c) {
runOnUiThread();
}
});

HeapSort heapSort = new HeapSort();
heapSort.heapIT();
}

public void runOnUiThread(){
Platform.runLater(new Runnable() {
@Override
public void run() {
hBox.getChildren().setAll(bars);
}
});
}
}
PS。当我在 HeapSort 中执行 heapIT 时,我填充了 bars 列表,我把它和算法留下了,因为它与我的问题无关(IMO)

图表示例图像:
enter image description here

最佳答案

您可能最好进行完整的 MVC。您已经完成大部分工作了。

让 Controller 告诉模型有关排序的更新。然后让 Controller 等待 GUI 更新。如何?当 Controller 将监听的转换完成时,让 GUI 通知模型。当 Controller 听到GUI已更新时,即可进行下一步操作。

您需要一个钩子(Hook)来知道排序何时完成。

FWIW:不完全熟悉 jaavafx 转换,所以我不确定如何监听转换完成,但我想有一种方法(覆盖方法或监听事件)

关于JavaFX 阻止非 UI 线程,直到 GUI 完成更新(暂停转换中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57877335/

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