JavaFX style class won't refresh

前端 未结 5 1165
说谎
说谎 2021-02-08 05:08

I\'m adding a style class to an node if it\'s selected and then remove it if I select other item. Even if I remove the style class the style wont refresh so it wont go back to n

5条回答
  •  自闭症患者
    2021-02-08 05:37

    Thanks for the solution posted by Uluk Biy. But it seems not work "as is" (tested on jdk 1.70_40 win x 64). I have to clear style class before settings class. Here the working code for me:

    import javafx.application.Application;
    import javafx.beans.property.BooleanProperty;
    import javafx.beans.property.SimpleBooleanProperty;
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.control.Label;
    import javafx.scene.layout.StackPane;
    import javafx.scene.layout.VBoxBuilder;
    import javafx.stage.Stage;
    
    public class StyleDemo extends Application {
        //ADD just a toggle property
        public static BooleanProperty toggle = new SimpleBooleanProperty(false);
    
        @Override
        public void start(Stage primaryStage) {
            final Label lbl = new Label("Style Me");
            lbl.getStyleClass().add("style1"); // initial style
    
            Button btn = new Button("Change the style");
    
            btn.setOnAction(new EventHandler() {
                @Override
                public void handle(ActionEvent event) {
                    //ADD clear style class !
                    lbl.getStyleClass().clear();
                    if(toggle.get()) {
                        lbl.getStyleClass().add("style1");
                        toggle.set(!toggle.get());
                    }else{
                        lbl.getStyleClass().add("style2");
                        toggle.set(!toggle.get());
                    }
                }
            });
    
            StackPane root = new StackPane();
            root.getChildren().add(VBoxBuilder.create().spacing(20).children(lbl,btn).build());
            Scene scene = new Scene(root, 300, 250); 
            scene.getStylesheets().add("/style.css");
            primaryStage.setScene(scene);
            primaryStage.show();
        }
    
        public static void main(String[] args) {
            launch(args);
        }
    }
    

提交回复
热议问题