这个错误通常发生在将FX应用程序的代码放在AWT线程中执行时。解决方法是将FX应用程序的代码放在FX应用程序线程中执行。以下是一个示例代码解决方法:
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javax.swing.*;
public class FXApplication extends Application {
@Override
public void start(Stage primaryStage) {
Button button = new Button("点击我");
button.setOnAction(e -> {
JOptionPane.showMessageDialog(null, "Hello World");
});
StackPane root = new StackPane();
root.getChildren().add(button);
Scene scene = new Scene(root, 300, 200);
primaryStage.setTitle("FX Application");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
// 在AWT线程中启动FX应用程序
Platform.startup(() -> {
// 在FX应用程序线程中运行FX应用程序
Application.launch(FXApplication.class, args);
});
});
}
}
在这个示例代码中,我们使用SwingUtilities.invokeLater()
将FX应用程序的启动放在AWT线程中,然后在Platform.startup()
方法中将FX应用程序的代码放在FX应用程序线程中执行。这样就避免了"不在FX应用程序线程上"的错误。