gpt4 book ai didi

java - 在我的例子中如何使用 javaFX Task - 不重复

转载 作者:行者123 更新时间:2023-12-01 11:28:43 27 4
gpt4 key购买 nike

我知道我的问题有答案,但我不明白代码中的问题。

为什么我得到:

java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread-4

我正在尝试使用 Controller 类中的方法将文本从任务添加到文本流,由于某种原因,程序在 .getChildren() 方法上失败。

在 Controller 类中调用 Spliter:

btnSplit.setOnMouseClicked(new EventHandler<Event>() {
@Override
public void handle(Event event) {
Thread split = new Thread(new Spliter(custToSplit, Controller.this));
split.setDaemon(true);
split.start();

}
});

类分割器构造器:

public Spliter(File f, Controller c){
this.c = c;
this.cust = f;

}
c.updateHebFlow("Dir created: "+ newDir.getAbsolutePath() , INFO_TEXT);

Controller 类的一部分:

@FXML
private TextFlow hebFlow;
@Override
public void initialize(URL location, ResourceBundle resources) {
assert hebFlow != null : "fx:id=\"hebFlow\" was not injected: check your FXML file 'MainXml.fxml'.";

public void updateHebFlow(String text,String type){
normalText = new Text();
errorText = new Text();
errorText.setFill(Color.RED);
infoText = new Text();
infoText.setFill(Color.BLUE);
switch(type){
case(ERROR_TEXT) :
errorText.setText(text);
hebFlow.getChildren().addAll(new Text("/n"), errorText);
break;
case(INFO_TEXT) :
infoText.setText(text);
hebFlow.getChildren().addAll(new Text("/n"), infoText);
break;
case(NORMAL_TEXT) :
normalText.setText(text);
hebFlow.getChildren().addAll(new Text("/n"), normalText);
break;
}
}
}

在 Spliter 类中调用 updateHebFlow:

try{
c.updateHebFlow("Script by TulTul", INFO_TEXT);
}catch (Exception e){
e.printStackTrace();
}

据我了解,除了 Controller 之外,我无法从其他类更改 UI,因此我在 Controller 类中创建了一个方法来进行更改并在任务类中调用它,为什么我会收到此异常?如果这是错误的,正确的方法是什么?

最佳答案

From what I understand I cant change the UI from other class other then the controller

实际上,正确的说法是:“除了 JavaFX UI 线程之外,您无法从任何线程更改 UI”。因此,解决方案是使用 Splitter 中的 Platform.runLater() 如下:

// Java 8
Platform.runLater(() -> {
c.updateHebFlow("Script by TulTul", INFO_TEXT);
});

// Java 7
Platform.runLater(new Runnable() {
public void run() {
c.updateHebFlow("Script by TulTul", INFO_TEXT);
}
});

Platform.runLater() 保证在 JavaFX UI 线程中并按调用顺序运行 block 。

关于java - 在我的例子中如何使用 javaFX Task - 不重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30613210/

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