Search code examples
cssjavafxtabpanel

Style for floating TabPane does not appear


Trying to customize a floating TabPane by adding a CSS file just like in the example below. The new style does not appear for floating tabpane only - for a regular pane the style appears as expected.

public class FloatingTabPaneTest extends Application
{
  public static void main(String[] args)
  {
    Application.launch(args);
  }

  @Override
  public void start(Stage stage)
  {
    Parent root = createContentPane();
    root.getStylesheets().add(getClass().getResource("/floatingTabPane.css").toExternalForm());        
    Scene scene = new Scene(root, 1000, 800);    
    stage.setScene(scene);

    stage.setTitle(getClass().getSimpleName());
    stage.show();
  }

  private Parent createContentPane()
  {
    TabPane tabPane = new TabPane();
    tabPane.getStyleClass().add(TabPane.STYLE_CLASS_FLOATING);

    addTab(tabPane, "Tab 1", new StackPane());
    addTab(tabPane, "Tab 2", new StackPane());
    addTab(tabPane, "Tab 3", new StackPane());
    tabPane.getSelectionModel().selectLast();

    return new BorderPane(tabPane);
  }

  private void addTab(TabPane tabPane, String name, Node content)
  {
    Tab tab = new Tab();
    tab.setText(name);
    tab.setContent(content);
    tabPane.getTabs().add(tab);    
  }  
}

FloatingTabPane.css:

    .tab-pane.floating > .tab-header-area > .tab-header-background {
    -fx-border-color: red;
    -fx-border-width: 2;
    -fx-background-color: cyan;
}

Solution

  • This is pretty interesting. The issue is because the headerBackground visibility is set to false, if you are on FLOATING style class.

    If you search inside TabPaneSkin, you will find :

    if (isFloatingStyleClass()) {
         headerBackground.setVisible(false); // <---- Imp part
    } else {
         headerBackground.resize(snapSize(getWidth()), snapSize(getHeight()));
         headerBackground.setVisible(true);
    }
    

    Since its visibility is set to false, your best shot is to do your changes on the tab-header-area instead of tab-header-background

    .tab-pane.floating > .tab-header-area {
        -fx-border-color: red;
        -fx-border-width: 2;
        -fx-background-color: cyan;
    }
    

    This will leave a thin red line on the tabs, but this is better than having no style at all ;)