Search code examples
javafxtabsfxml

Padding in FXML the content of a TabPane, but not the tab bar


I am looking for an elegant way of setting a padding to a TabPane, but without padding the tab bar:

<TabPane>
    <padding>
        <Insets top="10" bottom="10" right="10" left="10" />
    </padding>
    <Tab text="red">
        <Rectangle fill="RED" width="200" height="200" />
    </Tab>
    <Tab text="blue">
        <Rectangle fill="BLUE" width="200" height="200" />
    </Tab>
</TabPane>

gives: (unwanted) global padding

however,

<TabPane>
    <Tab text="red">
        <VBox>
            <padding>
                <Insets top="10" bottom="10" right="10" left="10" />
            </padding>
            <Rectangle fill="RED" width="200" height="200" />
        </VBox>
    </Tab>
    <Tab text="blue">
        <VBox>
            <padding>
                <Insets top="10" bottom="10" right="10" left="10" />
            </padding>
            <Rectangle fill="BLUE" width="200" height="200" />
        </VBox>
    </Tab>
</TabPane>

gives: Correct padding

which is exactly what i want, however I want to simplify the FXML structure, mainly by refactoring the <padding> element so it's declared in one place (shorter and non-repeating code) and not in every tab of the pane.

So is there any way to achieve this? Or am I stuck with my repeated <padding> elements? I'd prefer an FXML solution, but if no way exists a Java one is OK.


Solution

  • EDIT: I updated the answer to use the CSS selectors from fabian's comment down below.

    You can set padding for most JavaFX scene graph objects in a separate css file. You will need to link the css file to your FXML file which I will show below. The css file and the FXML file will need to be in the same directory, otherwise you will have to edit the value="..." tag.

    style.css

    .tab-pane > .tab-content-area > * {
        -fx-padding: 10 10 10 10;
    }
    

    This sets padding to all the VBoxes that happen to be under a Tab somewhere (no matter how deep in the hierarchy)

    main.fxml

    <TabPane>
        <Tab text="red">
            <VBox> 
                <Rectangle fill="RED" width="200" height="200" />
            </VBox>
        </Tab>
        <Tab text="blue">
            <VBox>
                <Rectangle fill="BLUE" width="200" height="200" />
            </VBox>
        </Tab>
    
        <stylesheets>
            <URL value="@style.css" />
        </stylesheets>
    </TabPane>