【问题标题】:JavaFX styles lost when loading an external Jar(plugin architecture)加载外部 Jar(插件架构)时 JavaFX 样式丢失
【发布时间】:2019-05-27 16:29:57
【问题描述】:

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

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

Core:有一个插件应该实现的接口(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 的类,我离开了 Main.java 以便它可以在两种模式下工作,一个应用程序和插件,但它不是真的必要

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的类

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);
    }
}

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

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

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

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

【问题讨论】:

    标签: java css javafx javafx-8


    【解决方案1】:

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

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

    它将查找相对于类路径的根名为style.css 的资源。这是因为没有方案;有关详细信息,请参阅documentation。问题是这种行为使用 ClassLoader 为 JavaFX 类加载资源。不幸的是,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 样式类只会自动添加到Scene 的根。您可能想要做的是设置自己的样式类并在 CSS 文件中使用 that


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

    【讨论】:

    • 感谢您的回答,我按照您的建议做了,现在 fxml 上的属性看起来像 stylesheets="@style.css",但我仍然收到正确路径的错误:com. sun.javafx.css.StyleManager loadStylesheetUnPrivileged 警告:找不到资源“jar:file:C:\Users\josegum\Zamba\plugins\Plugin-1.0-SNAPSHOT.jar!/style.css”。如您所见,斜线是这样的:\ 不是这样的:/。如果通过代码我用正确的斜杠加载文件一切正常,例如:getStylesheets().add("jar:file:C:/Users/josegum/Zamba/plugins/Plugin-1.0-SNAPSHOT.jar!/style. css");,有什么解决办法吗?
    • 我下载了你的项目,它成功了,我像你一样改变了加载 jar 到 ServiceLoader 的方式,现在一切正常,非常感谢兄弟,你是男人
    猜你喜欢
    • 1970-01-01
    • 2016-03-10
    • 2015-11-07
    • 1970-01-01
    • 1970-01-01
    • 2012-09-05
    • 2012-02-22
    • 2011-01-22
    • 1970-01-01
    相关资源
    最近更新 更多