Search code examples
javajavafxfxmlcentering

Centering buttons and text in a GridPane (JavaFX)


I have a simple display that has a title at the very top, a list in the middle, and then three buttons at the bottom. I want the title at the top and the buttons at the bottom to be horizontally centered.

Here is the code that I've been trying to use:

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

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.ListView?>
<?import javafx.scene.layout.GridPane?>

<GridPane
    xmlns="http://javafx.com/javafx/8.0.40"
    xmlns:fx="http://javafx.com/fxml/1"
    fx:controller="controllers.SongLibraryController"
>
    <Label
        text="Todo List"
        GridPane.columnSpan="3"
        GridPane.rowIndex="0"
        GridPane.halignment="CENTER"
    />
    <ListView
        prefWidth="300"
        prefHeight="400"
        fx:id="listView"
        GridPane.columnSpan="3"
        GridPane.rowIndex="1"
    />
    <Button
        fx:id="editItem"
        GridPane.halignment="CENTER"
        GridPane.columnIndex="0"
        GridPane.rowIndex="2"
        text="Edit Item"
    />
    <Button
        fx:id="addItem"
        GridPane.halignment="CENTER"
        GridPane.columnIndex="1"
        GridPane.rowIndex="2"
        text="Add Item"
    />
    <Button
        fx:id="deleteItem"
        GridPane.halignment="CENTER"
        GridPane.columnIndex="2"
        GridPane.rowIndex="2"
        text="Delete Item"
    />
</GridPane>

And here is the current output:

enter image description here

I've tried doing various things like using alignment="CENTER" for my GridPane, but nothing seems to be working. Any help would be appreciated!


Solution

  • You need to set alignment for your GridPane as alignment="center" and all elements will be aligned in center.

    Update You can align your buttons in center like this.

    <HBox GridPane.rowIndex="2" GridPane.columnSpan="3" alignment="CENTER" spacing="25">
        <Button text="b1"/>
        <Button text="b2"/>
        <Button text="b3"/>
    </HBox>
    

    After this update you also can delete columnSpan attribute from each node.