Search code examples
javajavafxmodel-view-controllerpositionfxml

FXML: positioning multiple elements within an horizontal Box(HBox)


Within an Hbox, i do want to have a text as a title, as well as an search bar with a submit button.

The title should be positioned on the left but the search bar with the submit button on the right.

The way i did it:

<HBox>  
    <Label text="Penfactory Software"/> 
    <HBox alignment="TOP_RIGHT">
        <TextField fx:id="idSearch"  />
        <Button fx:id="idSubmit" text ="Submit" onAction="#submit"/> 
    </HBox>
</HBox>

Hbox can give its elements an position with alignment ="TOP_RIGHT". The Issue: Only Top lvl HBox can give the alignment, otherly put, if there is a HBox within a HBox only the top-level HBox will determine where the elements are being placed.

How do i achieve the goal described above of having the title on the left and search + button on the right?


Solution

  • You have to add a Pane. Set the Pane's max-width to MAX_VALUE and Hgrow to ALWAYS.

    <?xml version="1.0" encoding="UTF-8"?>
    
    <?import javafx.scene.control.Button?>
    <?import javafx.scene.control.Label?>
    <?import javafx.scene.control.TextField?>
    <?import javafx.scene.layout.HBox?>
    <?import javafx.scene.layout.Pane?>
    <?import javafx.scene.text.Font?>
    
    
    <HBox maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1">
       <children>
          <Label text="Hello world!">
             <font>
                <Font size="17.0" />
             </font>
          </Label>
          <Pane maxHeight="-Infinity" maxWidth="1.7976931348623157E308" HBox.hgrow="ALWAYS" />
          <TextField />
          <Button mnemonicParsing="false" text="Button" />
       </children>
    </HBox>
    

    enter image description here