IDEA使用JFX的相关问题

1 问题概述

首先是javafx找不到对应的类:
在这里插入图片描述
其次是java

class com.sun.javafx.fxml.FXMLLoaderHelper (in unnamed module @0x50f36265) cannot access class com.sun.javafx.util.Utils (in module javafx.graphics) 
because module javafx.graphics does not export com.sun.javafx.util to unnamed module @0x50f36265

这种问题。
或者是bash

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

这样的问题。app

2 解决方案

环境Manjaro+OpenJDK11,首先须要确保有OpenJFX,可是,不能直接使用pacman/yaourt安装:
在这里插入图片描述
虽然看上去没什么问题,OpenJDK使用的也是pacman安装的,想着JFX也能够这样,安装以后在jvm

/usr/lib/jvm/java-11-openjdk/lib

下面确实有了JFX的文件,可是装了以后IDEA死活识别不出来,没办法,只能手动安装JFX。
手动安装的OpenJFX一加就立刻识别出来了,因此,手动安装吧,也不难,戳这里下载所须要的版本,解压到对应的位置,而后在IDEA中的外部库添加其中的lib文件夹便可:
在这里插入图片描述
添加以后另外一个问题是ui

class com.sun.javafx.fxml.FXMLLoaderHelper (in unnamed module @0x50f36265) cannot access class com.sun.javafx.util.Utils (in module javafx.graphics) 
because module javafx.graphics does not export com.sun.javafx.util to unnamed module @0x50f36265

给出的最多的答案是修改VM Options:this

--module-path=JFX_LIB_PATH --add-modules=javafx.controls,javafx.fxml

其中JFX_LIB_PATH是JFX下的lib目录路径,可是不行,另外一个方案是在源文件目录下添加module-info.java:spa

module javafx.graphics{
    exports com.sun.javafx.util
}

也不行,直接报错,而后又搜索到了另外一个解决办法,额外添加一个相似启动类的java文件,好比叫App.java:code

import javafx.application.Application;

public class App {
    public static void main(String[] args) {
        Application.launch(Main.class,args);
    }
}

而后修改IDEA的运行配置,把主类修改成App。
这样笔者的问题就解决了,能够正常运行JFX程序了。component

3 其余问题

Caused by: java.lang.NullPointerException: Location is required.

其中一个可能的办法是:xml

Parent root = FXMLLoader.load(getClass().getResource("xxx.fxml"));

改成:

Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("xxx.fxml"));

笔者试过,这个方法不行,另外一个解决的方法是,修改pom.xml:

<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
                <includes>
                    <include>**/*.fxml</include>
                </includes>
            <filtering>false</filtering>
        </resource>
    </resources>
</build>

其中include中的两个星号指的是fxml的文件夹的位置。
笔者试过这个方法可行,若fxml文件在源码根目录,能够修改成:

<include>*.fxml</include>