要解决这个问题,您需要将代码放在FX应用线程上。以下是一个示例:
import javafx.application.Application;
import javafx.application.Platform;
import javafx.stage.Stage;
public class MyApp extends Application {
@Override
public void start(Stage primaryStage) {
// 在FX应用线程上执行代码
Platform.runLater(() -> {
// 在这里写下您的代码
// ...
// 检查当前线程
String threadName = Thread.currentThread().getName();
System.out.println("currentThread = " + threadName);
});
}
public static void main(String[] args) {
launch(args);
}
}
在上面的示例中,我们使用Platform.runLater()
方法将代码放在FX应用线程上执行。在该方法的lambda表达式中,您可以编写您的代码。然后,您可以使用Thread.currentThread().getName()
来获取当前线程的名称。
请注意,在FX应用线程上运行的代码应该是非阻塞的,以避免阻塞应用程序的UI响应。