Can't load css file in javafx 8

后端 未结 2 667
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-25 05:30
Scene listenMenu = new Scene(root, 250, 272);
listenMenu.getStylesheets().add(\"styles.css\");

This always worked for me to load my css file, but after

2条回答
  •  一个人的身影
    2021-01-25 06:16

    try this: create a Java file

    import javafx.application.Application;
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.layout.StackPane;
    import javafx.stage.Stage;
    
    public class HelloStyledWorld extends Application {
    
        @Override
        public void start(Stage primaryStage) {
            Button btn = new Button();
            btn.setText("Say 'Hello Styled World'");
            btn.setOnAction(new EventHandler() {
    
                @Override
                public void handle(ActionEvent event) {
                    System.out.println("Hello Styled World!");
                }
            });
    
            StackPane root = new StackPane();
            root.getChildren().add(btn);
    
            Scene scene = new Scene(root, 300, 250);
            scene.getStylesheets().add(getClass().getResource("style.css").toExternalForm());
    
            primaryStage.setTitle("Hello Styled World!");
            primaryStage.setScene(scene);
            primaryStage.show();
        }
    
        public static void main(String[] args) {
            launch(args);
        }
    }
    

    put the style.class in the same package as the .java file (or in the corresponding resource folder if you are using one.

    verify that the build includes the correct css file into output folder. you can

    System.out.println(getClass().getResource("style.css").toExternalForm());
    

    to console to see where JavaFX is searching for the css and check if the css is available there.

提交回复
热议问题