Edit JavaFX CSS at runtime

前端 未结 1 2043
粉色の甜心
粉色の甜心 2021-02-06 13:28

I\'m creating a CSS stylesheet for a JavaFX 8 application.

I\'m repeating these steps several times:

  1. Edit the CSS
  2. Run the application and see the
1条回答
  •  一整个雨季
    2021-02-06 14:01

    You will have to change using getStylesheets() / setStyle() etc.

    In the example below I had to use a temp file as I am changing the CSS of the scene, when using into single components this is not necessary as you can change directly in the components.

    enter image description here

    You may download this example on gist.

    Test.java

    import javafx.application.Application;
    import javafx.fxml.FXMLLoader;
    import javafx.scene.Parent;
    import javafx.scene.Scene;
    import javafx.stage.Stage;
    
    public class Test extends Application{
    
        @Override
        public void start(Stage primaryStage) throws Exception {
            FXMLLoader loader = new FXMLLoader(getClass().getResource("doc.fxml"));
            Parent root = (Parent)loader.load();
            CSSController myController = loader.getController();
            Scene scene = new Scene(root);
            myController.setScene(scene);
            primaryStage.setScene(scene);
            primaryStage.show();
        }
        public static void main(String[] args) {
            launch(args);
        }
    
    }
    

    CSSController.java

    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    import java.net.URL;
    import java.util.ResourceBundle;
    
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.fxml.FXML;
    import javafx.fxml.Initializable;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.control.TextArea;
    
    public class CSSController implements Initializable{
        private Scene scene;
        @FXML TextArea cssContent;
        @FXML Button defineCSSButton;
        @Override
        public void initialize(URL location, ResourceBundle resources) {
            defineCSSButton.setOnAction(new EventHandler(){
                @Override
                public void handle(ActionEvent event) {
                    String css = cssContent.getText();
                    try{
                        File temp = new File("tempfile.css"); 
                        temp.delete();
                        temp.createNewFile();
                        BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
                        bw.write(css);
                        bw.close();
                        String url = "tempfile.css";
                        scene.getStylesheets().add(temp.toURI().toString());
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                }
            });    
        }
        public void setScene(Scene scene) { this.scene = scene; }
    }
    

    doc.fxml