Add uneven spacing between elements in a HBox FXML

1.4k Views Asked by At

I want to add spacing between the ComboBox and the TextField. I added spacing to the Box however since there are 4 nodes in the HBox, it adds spacing to all of them which isn't what I want. I want the TextField to be on the right of the window. I was thinking of adding an invisible separator with a large width however I read that regions can be used but I'm unsure on how to use them in FXML.

This is the code I have currently, but unsure how to add a region to it.

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<?import javafx.scene.text.TextFlow?>
<BorderPane prefHeight = "200.0" prefWidth = "300.0" xmlns = 
    <top>
        <HBox alignment = "CENTER_LEFT" prefWidth = "300.0" spacing = "5">
            <padding>
                <Insets topRightBottomLeft="50" />
            </padding>
            <Label>Sort by: </Label>
            <ComboBox fx:id = "sortOrder" promptText = "Select" />

        </HBox>
    </top>
</BorderPane>
1

There are 1 best solutions below

0
On

Don't hard-code preferred sizes.

To make the text field sit at the right edge of the HBox, add an empty Region between the ComboBox and TextField. Set the region's hgrow parameter to ALWAYS, so any extra space will get allocated to it:

<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<?import javafx.scene.text.TextFlow?>
<BorderPane  xmlns = "http://javafx.com/javafx/16" xmlns:fx = "http://javafx.com/fxml/1" >
    <top>
        <HBox alignment = "CENTER_LEFT"  spacing = "5">
            <padding>
                <Insets topRightBottomLeft="20" />
            </padding>
            <Label>Sort by: </Label>
            <ComboBox fx:id = "sortOrder" promptText = "Select" />
            <Label>Search by host name: </Label>
            <Region HBox.hgrow="ALWAYS" />
            <TextField fx:id = "hostName" />
        </HBox>
    </top>
</BorderPane>

enter image description here

After stretching the window:

enter image description here

You can further control the behavior if you need; e.g. to let the text field grow, set it's maxWidth to Infinity and set the maxWidth of the Region. Other solutions are possible; e.g. put the label and combo box in a HBox, and then wrap the HBox and TextField in a BorderPane, with the HBox in the left and the TextField in the right.