加载外部 Jar(插件架构)时 JavaFX 样式丢失

JavaFX styles lost when loading an external Jar(plugin architecture)

我正在尝试创建一个可以使用插件的 JavaFX 应用程序,这些插件是在运行时加载的其他 jar,并打开以查找我创建的特定接口的实现,我能够加载 jar并找到具体的class但是加载的jar无法加载的一些样式,让我解释一下我做了什么:

我创建了三个maven项目,这些项目如下:

核心: 有一个插件应该实现的接口(TestPlugin.java),和一个主程序应该实现的接口(TestSceneHandler.java)

TestPlugin.java

public interface TestPlugin {

    void init(TestSceneHandler sceneHandler);

}

TestSceneHandler.java

import javafx.scene.Parent;

public interface TestSceneHandler {

    void setView(Parent node);

}

Plugin:有 Core 作为依赖项和实现 TestPlugin.java 的 class,我离开了Main.java 所以它可以在两种模式下工作,sigle 应用程序和插件,但它并不是真正必要的

MyTestViewController.java

import javafx.fxml.FXMLLoader;
import javafx.scene.layout.GridPane;
import java.io.IOException;

public class MyTestViewController extends GridPane {

    public MyTestViewController() {
        FXMLLoader fxmlLoader = new FXMLLoader(this.getClass().getResource("/pluginView.fxml"));
        fxmlLoader.setClassLoader(getClass().getClassLoader());
        fxmlLoader.setRoot(this);
        fxmlLoader.setController(this);

        try {
            fxmlLoader.load();
        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }
    }

}

TestPluginImpl.java

package sample;

public class TestPluginImpl implements TestPlugin {
    @Override
    public void init(TestSceneHandler testSceneHandler) {
        testSceneHandler.setView(new MyTestViewController());
    }
}

Main.java

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(new MyTestViewController(), 300, 275));
        primaryStage.show();
    }


    public static void main(String[] args) {
        launch(args);
    }
}

pluginView.fxml

<?import javafx.scene.layout.GridPane?>

<?import javafx.scene.control.Label?>
<fx:root  xmlns:fx="http://javafx.com/fxml/1"
          type="javafx.scene.layout.GridPane"
          alignment="center" hgap="10" vgap="10" stylesheets="style.css">
    <Label>
        Hello world
    </Label>
</fx:root>

style.css

.root {
    -fx-background-color: red;
}

App:具有 Core 作为依赖项和实现 TestSceneHandler.java[=23 的 class =]

Main.java

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(new TestScene(), 300, 275));
        primaryStage.show();
    }


    public static void main(String[] args) {
        launch(args);
    }
}

sample.fxml

<?import javafx.scene.layout.HBox?>
<?import javafx.scene.control.Label?>
<fx:root xmlns:fx="http://javafx.com/fxml/1"
     type="javafx.scene.layout.BorderPane">

    <top>
        <HBox style="-fx-background-color: orange;">
            <children>
                <Label>
                    This is the header
                </Label>
            </children>
        </HBox>
    </top>

</fx:root>

TestScene.java

import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.layout.BorderPane;

import java.io.*;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.zip.ZipFile;

public class TestScene extends BorderPane implements TestSceneHandler {

    private static final String ROOT_FOLDER = "Zamba";
    private static final String PLUGIN_FOLDER = "plugins";
    private static final String USER_HOME = System.getProperty("user.home");

    public TestScene() {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/sample.fxml"));
        fxmlLoader.setRoot(this);
        fxmlLoader.setController(this);

        try {
            fxmlLoader.load();
        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }

        File pluginFolder = initFolder();
        readPlugins(pluginFolder);
    }

    private File initFolder() {
        final String ROOT_FOLDER_PATH = USER_HOME + "/" + ROOT_FOLDER;
        final String PLUGIN_FOLDER_PATH = ROOT_FOLDER_PATH + "/" + PLUGIN_FOLDER;

        File appFolder = new File(ROOT_FOLDER_PATH);

        if(!appFolder.exists()) {
            appFolder.mkdir();
        }

        File pluginFolder = new File(PLUGIN_FOLDER_PATH);

        if(!pluginFolder.exists()) {
            pluginFolder.mkdir();
        }

        return pluginFolder;
    }

    /**
     * Determine whether a file is a JAR File.
     */
    public static boolean isJarFile(File file) throws IOException {
        if (!isZipFile(file)) {
            return false;
        }
        ZipFile zip = new ZipFile(file);
        boolean manifest = zip.getEntry("META-INF/MANIFEST.MF") != null;
        zip.close();
        return manifest;
    }
    /**
     * Determine whether a file is a ZIP File.
     */
    public static boolean isZipFile(File file) throws IOException {
        if(file.isDirectory()) {
            return false;
        }
        if(!file.canRead()) {
            throw new IOException("Cannot read file "+file.getAbsolutePath());
        }
        if(file.length() < 4) {
            return false;
        }
        DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
        int test = in.readInt();
        in.close();
        return test == 0x504b0304;
    }

    private void readPlugins(File pluginFolder) {
        File[] pluginFolderFiles = pluginFolder.listFiles();
        Arrays.asList(pluginFolderFiles).forEach(file -> {
            System.out.println("Filee: " + file.getAbsolutePath());

            try {
                if(isJarFile(file)) {
                    JarFile jarFile = new JarFile(file);

                    Enumeration<JarEntry> e = jarFile.entries();

                    URL[] urls = { new URL("jar:file:" + file.getAbsolutePath()+"!/") };
                    URLClassLoader cl = URLClassLoader.newInstance(urls);

                    while (e.hasMoreElements()) {
                        JarEntry je = e.nextElement();

                        if(je.isDirectory() || !je.getName().endsWith(".class")){
                            continue;
                        }

                        // -6 because of .class
                        String className = je.getName().substring(0,je.getName().length()-6);
                        className = className.replace('/', '.');

                        Class c = cl.loadClass(className);

                        if(TestPlugin.class.isAssignableFrom(c) && c != TestPlugin.class) {
                            System.out.println("Plugin found!!!");

                            TestPlugin plugin = (TestPlugin)c.newInstance();
                            plugin.init(this);
                        }

                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    @Override
    public void setView(Parent parent) {
        setCenter(parent);
    }
}

将项目 Plugin 作为独立应用程序执行时,结果如下:

但是当通过App项目执行时,结果如下:

如您所见,样式已消失,控制台出现错误:

Plugin found!!!
dic 30, 2018 5:41:30 PM com.sun.javafx.css.StyleManager loadStylesheetUnPrivileged
WARNING: Resource "style.css" not found.

问题是由 class 路径问题引起的,因为您正在创建自己的 ClassLoader 来加载您的插件。 FXML 中 stylesheet 属性的值为 style.css。这与做的一样:

GridPane pane = new GridPane();
pane.getStylesheets().add("style.css");

这将查找相对于 class 路径的根目录的名为 style.css 的资源。这是因为没有方案;有关详细信息,请参阅 documentation。问题是此行为使用 JavaFX classes 的 ClassLoader 来加载资源。不幸的是,您的资源对 ClassLoader 不可见,对您为加载插件而创建的 ClassLoader 可见。

解决此问题的方法是为 CSS 资源文件提供完整的 URL。这是通过使用 @ 完成的(参见 Introduction to FXML)。使用 @ 时,位置是相对于 FXML 文件的。例如,如果您的 FXML 文件是 /fxml/PluginView.fxml 而您的 CSS 文件是 /styles/style.css,您将有:

<?import javafx.scene.control.Label?>
<fx:root  xmlns:fx="http://javafx.com/fxml/1"
          type="javafx.scene.layout.GridPane"
          alignment="center" hgap="10" vgap="10" stylesheets="@../styles/style.css">
    <Label>
        Hello world
    </Label>
</fx:root>

这将调用 getStylesheets().add(...) 类似的内容:

jar:file:///path/to/plugin/file.jar!/styles/style.css

不管使用什么ClassLoader都可以找到。


另一个可能的问题是在您的 style.css 文件中。您使用 .root {}root 样式 - class 只会自动添加到 Scene 的根中。您可能想要做的是设置您自己的样式 -class 并在 CSS 文件中使用 that


此外,您正在编写自己的插件发现和加载代码。并不是说你不能继续做你正在做的事情,但我只是想让你知道你不必重新发明轮子。 Java 有 java.util.ServiceLoader 正是这种事情。