Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
665 views
in Technique[技术] by (71.8m points)

javafx - What is wrong with my syntax calling a stylesheet (css) from an FXML file?

I am working in NetBeans 8, with Java 8 / JavaFX and FXML.

In the first controller (an AnchorPane) in my FXML document, I have this, that works:

stylesheets="file:///C:/Users/me/Documents/NetBeansProjects/MyApp/src/myApp/myStyle.css"

However, when I attempt to replace that with any type of relative path, I get the following error at runtime:

com.sun.javafx.css.StyleManager loadStylesheetUnPrivileged
WARNING: Resource "myStyle.css" not found.

I tried

stylesheets="myStyle.css"
stylesheets="file://myStyle.css"
stylesheets="./myStyle.css"
stylesheets="css/myStyle.css"

(where I put a copy of the css file in a subdirectory from where it was)

...and maybe 50 other permutations. Every time I get the same error.

The reason I care is that I am having a second problem. In the first version, that works on my machine... when I take my jar file to another machine, the css is not applied when the application is run... It's like the resource file isn't copied.

Help?

Thanks!

-Adeena

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Let me consider your project structure as follows

MyApp
  |
  |_ src
      |
      |_controllers (Controllers)
      |_view (FXML)
      |_style (css)
          |_myStyle.css

You can specific the relative path in the FXML using

<stylesheets>
   <URL value="@../style/myStyle.css" />
</stylesheets>

In your controller, you can add it as follows

layout.getStylesheets().add(getClass().
         getResource("/style/myStyle.css")).toExternalForm();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...