简体   繁体   English

如何从外部捆绑资源导入CSS文件

[英]How to import a CSS file from an external bundle resource

I'm trying to import an OSGi bundle resource (a CSS file called style.css) from another bundle called cssBundle : 我正在尝试从另一个名为cssBundle的捆绑包中导入OSGi捆绑包资源(一个名为style.css的CSS文件)

public void addCSS() {
    Bundle bundle = FrameworkUtil.getBundle(this.getClass());
    Bundle[] bArray = bundle.getBundleContext().getBundles();
    Bundle cssBundle = null;
    for (Bundle b : bArray) {
        if (b.getSymbolicName().equals("cssBundle")) {
            cssBundle = b;
            break;
        }
    }
    Enumeration<URL> resources = null;
    try {
        resources = cssBundle.getResources("/resources/css/mainscreen.css");
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (resources != null) {
        URL myCSSURL = resources.nextElement();
        try {
            URI uri = myCSSURL.toURI();
            File f = new File(uri);
            scene.getStylesheets().add("file:///" + f.getAbsolutePath().replace("\\", "/"));
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }
}

However, this way, I get: 但是,这样,我得到:

Exception in thread "JavaFX Application Thread" java.lang.IllegalArgumentException: URI scheme is not "file"
at java.io.File.<init>(Unknown Source)

What would be the right, or better way to go about it? 什么是正确的或更好的解决方案?

System.out.println(myCSSURL);

OUTPUTS 输出值

bundle://13.1:1/resources/css/style.css  

Is there a way I could add this onto my Scene without using URLs? 有没有一种方法可以在不使用URL的情况下将其添加到我的场景中?

The URI represeting the resource from the bundle can not be represented as a file. 从分发包重新设置资源的URI不能表示为文件。 So the approach to create a file from the URI is not possible. 因此,无法从URI创建文件的方法。

What you can do with the bundle resource is to get an InputStream for it. 您可以使用bundle资源来为其获取InputStream。 So you can use this to copy the stream contents to a file in the temp folder and give that file to scene.getStylesheets().add. 因此,您可以使用它来将流内容复制到temp文件夹中的文件中,并将该文件提供给scene.getStylesheets()。add。

Another approach might be to define an Import-Package in your bundle for resources.css. 另一种方法可能是在包中为resource.css定义一个Import-Package。 This will make the file available on the classpath of your bundle. 这将使文件在包的类路径上可用。 So maybe the scene.getStylesheets().add("/resources/css") will then work. 因此,也许scene.getStylesheets()。add(“ / resources / css”)将可以正常工作。

That exception means it cannot find your file. 该异常意味着它找不到您的文件。 You should investigate creating a URI to the CSS file. 您应该研究如何创建CSS文件的URI。

URI uri = new URI("file:///C:/other/mydir/myfile.txt");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM