第一次使用 JavaFX,我尝试使用 Hello World!
窗口对其进行测试。
我在 Mojave 10.14.5 的 MacOS 上使用 Java 8(更新 211)和 Eclipse。
我正在做这个项目:
我将我认为需要的所有 JavaFX jar 放入构建路径中(也许我丢失了一些 jar?)。
我正在尝试使用以下代码通过 JavaFX 打开一个窗口:
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Test extends Application{
public static void main(final String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Hello World!");
Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("Hello World!");
}
});
StackPane root = new StackPane();
root.getChildren().add(btn);
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.show();
}
}
代码应该没问题,因为它可以在 Windows 和 Linux 上运行。
当我运行它时,下面的栏中会出现一个 java 项目,正如您在此处看到的:
我知道它已打开,因为它下面有一个小点,但我看不到任何窗口。此外,我无法在不关闭 Eclipse 本身的情况下关闭这个“一杯咖啡”项目。
编辑: 我从 IDE (Eclipse 4.9.0) 运行它。使用 Oracle 的 Java 8 (211)。我自己添加了引用的库,如果我尝试删除它们并将导入保留在代码中,则会收到此错误:
Access restriction: The type 'Application' is not API (restriction on required library '/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/jre/lib/ext/jfxrt.jar')
最佳答案
问题解决了!问题出在包上:javafx-swt.jar
In the Eclipse IDE for Mac, when a Java program references SWT, the IDE automatically adds the VM option -XstartOnFirstThread. In most cases, this automatic addition is helpful. However, there is one case when adding this VM option causes a problem, namely with an Eclipse project for an SWT application that also includes one or more "pure" JavaFX classes that do not interoperate with the SWT classes. A "pure" JavaFX application that is launched from such an Eclipse project will hang because it does not expect -XstartOnFirstThread. (https://docs.oracle.com/javafx/2/swt_interoperability/jfxpub-swt_interoperability.htm)
在“运行配置”的“参数”选项卡中,您可以找到一个复选框,要求不使用 -XstartOnFirstThread。取消选中它,它就可以工作。
关于java - 无法在 MacOS 上启动 JavaFX 应用程序(使用 Java 8),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56776190/