且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在IntelliJ IDEA中使用JavaFX和Java 11

更新时间:2022-01-01 01:09:47

为您的操作系统下载适当的JavaFX SDK,并将其解压缩到所需的位置,例如/Users/your-user/Downloads/javafx-sdk-11

Download the appropriate JavaFX SDK for your operating system and unzip it to a desired location, for instance /Users/your-user/Downloads/javafx-sdk-11.

  1. 创建一个JavaFX项目

创建JavaFX项目为该项目提供一个名称,例如HelloFX,并提供一个位置.当项目打开时,无法识别JavaFX类.

Create a JavaFX project Provide a name to the project, like HelloFX, and a location. When the project opens, the JavaFX classes are not recognized.

  1. 设置JDK 11

转到文件"->项目结构"->项目",然后将项目SDK设置为11.您还可以将语言级别设置为11.设置JDK 11

Go to File -> Project Structure -> Project, and set the project SDK to 11. You can also set the language level to 11. Set JDK 11

  1. 创建一个库

转到文件->项目结构->库,然后将JavaFX 11 SDK作为库添加到项目中.指向JavaFX SDK的lib文件夹.

Go to File -> Project Structure -> Libraries and add the JavaFX 11 SDK as a library to the project. Point to the lib folder of the JavaFX SDK.

一旦应用了库,JavaFX类将被IDE识别.

Once the library is applied, the JavaFX classes will be recognized by the IDE.

警告:如果现在运行该项目,它将编译,但会出现此错误:

Warning: If you run now the project it will compile but you will get this error:

错误:缺少JavaFX运行时组件,它们是运行所必需的 此应用程序

Error: JavaFX runtime components are missing, and are required to run this application

由于Java 11启动器检查主类是否扩展javafx.application.Application,因此显示此错误.如果是这种情况,则需要在模块路径上具有javafx.graphics模块.

This error is shown since the Java 11 launcher checks if the main class extends javafx.application.Application. If that is the case, it is required to have the javafx.graphics module on the module-path.

  1. 添加VM选项

要解决此问题,请单击运行"->编辑配置...",然后添加以下VM选项:

To solve the issue, click on Run -> Edit Configurations... and add these VM options:

-module-path%PATH_TO_FX%--add-modules = javafx.controls,javafx.fxml

--module-path %PATH_TO_FX% --add-modules=javafx.controls,javafx.fxml

请注意,IntelliJ创建的默认项目使用FXML,因此javafx.fxml与javafx.controls一起是必需的.如果您的项目使用其他模块,则还需要添加它们. 单击应用",然后关闭对话框.

Note that the default project created by IntelliJ uses FXML, so javafx.fxml is required along with javafx.controls. If your project uses other modules, you will need to add them as well. Click apply and close the dialog.

  1. 运行项目

单击运行"->运行..."以运行该项目,现在它应该可以正常运行.

Click Run -> Run... to run the project, now it should work fine.