javajavafxjava-8javafx-8scenebuilder

How to right align a button in Java FX toolbar


I am building a UI using Java FX scene builder and I want a button in a toolbar to float towards the right side of the toolbar. I have tried changing the node orientation of the parent(toolbar) and also the button but both seem to be ignored.


Solution

  • Raw FXML using the "spring" method.

    Add a pane with no content which always grows to fit available space between the left aligned tools in the bar and right aligned ones. The pane functions as a "spring" that shrinks and stretches as needed.

    tool

    <?xml version="1.0" encoding="UTF-8"?>
    
    <?import javafx.scene.control.*?>
    <?import javafx.scene.layout.*?>
    
    <ToolBar prefHeight="40.0" prefWidth="318.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8">
       <Button text="Apples" />
       <Button text="Oranges" />
       <Pane HBox.hgrow="ALWAYS" />
       <Button text="Help" />
    </ToolBar>
    

    Using Scene Builder

    With this method, you cannot modify the Pane HBox.hgrow section directly in SceneBuilder. However, you can modify the setting outside of SceneBuilder and SceneBuilder will respect it.

    1. Create your toolbar with the added Pane in SceneBuilder.
    2. Save the fxml file in SceneBuilder.
    3. Edit the fxml file to add the attribute HBox.hgrow="ALWAYS" to the Pane.
    4. Ensure that you have matching imports in the fxml as shown in the example above (otherwise the right types for the HBox.hgrow layout will not be imported).
    5. When you save the fxml text file, SceneBuilder will automatically read the new version from the text file and update its display accordingly.