问题
I've read through every article/post I can find about this error, and I've tried every solution mentioned and the error is still being produced at run time. So here's my code, and below that is the error message from the console:
public class Driver extends Application {
public static void main(String[] args) {
launch(args);
} // main
@Override
public void start(Stage primaryStage) {
Parent root = null;
File css = new File("stylesheet.css");
try {
root = FXMLLoader.load(getClass().getResource("project-3.fxml"));
root.getStylesheets().clear();
root.getStylesheets().add("file:///" + css.getAbsolutePath().replace("\\", "/"));
} catch (IOException e) {
System.out.println(e);
System.exit(1);
} // try
primaryStage.setTitle("Programmer's Calculator");
primaryStage.setScene(new Scene(root, 397, 376));
primaryStage.show();
} // start
} // Driver
I've excluded the import statements to save space - they're not the issue.
Here's the error produced:
com.sun.javafx.css.StyleManager loadStylesheetUnPrivileged INFO: Could not find stylesheet: file:////Users/UserName/Documents/Names-p3/stylesheet.css
Here's my directory:
Here's what I've tried:
- Created a scene variable and tried applying the css stylesheet to that
- Added the 'stylesheets' modifier or whatever it's called to the Pane element in my fxml file, like this:
<Pane stylesheets="stylesheet.css"> - Changed the directory naming to everything imaginable...
Literally nothing is working. What is going on?
回答1:
Put the file containing your stylesheet in the src folder and then apply it to your root.
root = FXMLLoader.load(getClass().getResource("project-3.fxml"));
root.getStylesheets().add(getClass().getResource("your_stylesheet.css").toExternalForm());
Or
root.getStylesheets().add(getClass().getResource("your_stylesheet.css").toString());
回答2:
One simple solution is add at sign to FXML like this.
<Pane stylesheets="@stylesheet.css">
rather than:
<Pane stylesheets="stylesheet.css">
More info https://docs.oracle.com/javase/8/javafx/api/javafx/fxml/doc-files/introduction_to_fxml.html
回答3:
The following have worked for me:
- Resources (file has to be with the class files):
scene.getStylesheets().add(getClass().getResource("style.css").toString()); - Relative (files in working dir):
scene.getStylesheets().add("file:style.css"); - Absolute (files still in working dir):
scene.getStylesheets().add("file:/"+System.getProperty("user.dir").replace("\\", "/")+"/style.css");
It would seem that it's looking for the format of: file:<path> and for absolute paths its still looking for that root '/' even on windows. It also doesn't seem to like backslash '\' in the path.
来源:https://stackoverflow.com/questions/33764821/loadstylesheetunprivileged-error-when-trying-to-use-css-stylesheet-with-javafx