首页 文章

如何在代码中设置JavaFX TabPane CSS?

提问于
浏览
0

https://stackoverflow.com/a/10615258/529411

我想动态地为我的tabpane添加背景颜色(取决于某些条件) . 我怎样才能从代码中实现这一目标?一个选项是为他分配一个具有相关CSS的特定ID,但在我的情况下,颜色可以由用户动态选择 .

另外,我很好奇如何在处理组件层次结构时在代码中应用样式 .

1 回答

  • 2

    您可以在CSS文件中将背景颜色指定为looked-up color

    .tab-pane > .tab-header-area > .tab-header-background {
        -fx-background-color: -fx-outer-border, -fx-text-box-border, my-tab-header-background ;
    }
    

    现在,在代码中,您可以在需要时设置查找颜色的值:

    tabPane.setStyle("my-tab-header-background: blue ;");
    

    SSCCE:

    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.Tab;
    import javafx.scene.control.TabPane;
    import javafx.stage.Stage;
    
    public class DynamicTabHeaderBackground extends Application {
    
        private static final String TAB_HEADER_BACKGROUND_KEY = "my-tab-header-background" ;
    
        @Override
        public void start(Stage primaryStage) {
            TabPane tabPane = new TabPane();
            tabPane.setStyle(TAB_HEADER_BACKGROUND_KEY+": blue ;");
            tabPane.getTabs().addAll(new Tab("Tab 1"), new Tab("Tab 2"));
            tabPane.getSelectionModel().selectedIndexProperty().addListener((obs, oldIndex, newIndex) -> {
                if (newIndex.intValue() == 0) {
                    tabPane.setStyle(TAB_HEADER_BACKGROUND_KEY+": blue ;");
                } else {
                    tabPane.setStyle(TAB_HEADER_BACKGROUND_KEY+": green ;");
                }
            });
    
            Scene scene = new Scene(tabPane, 400, 400);
            scene.getStylesheets().add("dynamic-tab-header.css");
            primaryStage.setScene(scene);
            primaryStage.show();
        }
    
        public static void main(String[] args) {
            launch(args);
        }
    }
    

    with dynamic-tab-header.css包含上面的CSS代码 .

    Update

    如果您有多个选项卡窗格,则可能需要考虑以下CSS文件的变体:

    .tab-pane {
        my-tab-header-background: derive(-fx-text-box-border, 30%) ;
    }
    
    .tab-pane > .tab-header-area > .tab-header-background {
        -fx-background-color: -fx-outer-border, -fx-text-box-border, 
            linear-gradient(from 0px 0px to 0px 5px, -fx-text-box-border, my-tab-header-background) ;
    }
    

    这基本上模拟了默认行为,但允许您通过像以前一样调用 tabPane.setStyle(...) 代码来修改任何特定选项卡窗格上的背景 .

相关问题