adding css file to stylesheets in javafx

前端 未结 18 1180
[愿得一人]
[愿得一人] 2020-12-06 05:27

Language: JavaFX

IDE: Netbeans

Problem: I\'m trying to add a css file to the stylesheet, but the first line of the following code always generates a Nu

相关标签:
18条回答
  • 2020-12-06 05:42

    All of the answers are missing one very important part and that's '/' before the name of the css file:

    Folder structure:

    src
      resources
        stylesheet.css
    

    Load it like this, notice the starting slash before css file:

    scene.getStylesheets().add(getClass().getResource("/stylesheet.css").toExternalForm())
    
    0 讨论(0)
  • 2020-12-06 05:42

    I made a small login example and this is how i link my styleshet.css

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("LoginUI.fxml"));
    
    
        Scene scene = new Scene(root);
    
        scene.getStylesheets().add(JavaFXLogin.class.getResource("stylesheet.css").toExternalForm());
    
        stage.setScene(scene);
        stage.show();
    
    }
    

    You can use this code line to link your css file. but the css file should be in your package.

    scene.getStylesheets().add(JavaFXLogin.class.getResource("stylesheet.css").toExternalForm());

    0 讨论(0)
  • 2020-12-06 05:46

    Try putting '@' the name of the file. It worked for me.

    ex: '@main.css'

    0 讨论(0)
  • 2020-12-06 05:48

    I think your're missing the slashes which causes that the CSS file can't be found. Try to correct your path reference.

    For example:

    -root
    --app/Main.java
    --assets/double_slider.css
    

    would be:

    String css = this.getClass().getResource("/assets/double_slider.css").toExternalForm();
    
    0 讨论(0)
  • 2020-12-06 05:48

    I had the same problem (in NetBeans 8). I found a solution here : https://blog.idrsolutions.com/2014/04/use-external-css-files-javafx/

    My resource file spreadsheet.css was here :

    MyApp
    -resources
    --spreadsheet.css
    -source packages
    --fr.ccc.myapp.view
    ---mainView.java
    ---FXMLMain.fxml
    

    In mainView.java :

    File f = new File("resources/spreadsheet.css");
    spreadsheet.getStylesheets().add("file:///" + f.getAbsolutePath().replace("\\", "/"));
    

    Hope this helps.

    0 讨论(0)
  • 2020-12-06 05:48
    scene.getStylesheets().add("file:///home/fullpathname/file.css");
    

    or

    scene.getStylesheets().add("file:/home/fullpathname/file.css");
    

    but after:

    Run / Clean and Build Project

    worked for me

    NetBeans IDE 8.2 ; Java: 1.8.0_201 ;Linux 16.04

    0 讨论(0)
提交回复
热议问题