Reputation: 53799
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:
I've tried doing various things like using alignment="CENTER"
for my GridPane, but nothing seems to be working. Any help would be appreciated!
Upvotes: 1
Views: 8498
Reputation: 1787
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.
Upvotes: 3
Reputation: 762
To align elements inside a grid pane programatically, you will have to call static methods from the GridPane class.
To set horizontal alignment, call GridPane.setHalignment(Node n, HPos p)
. To set vertical alignment, call GridPane.setValignment(Node n, VPos p)
.
You can read Oracle's own layout guide here. If you scroll down until you see the pie chart, they show an example of how to manage layouts in grid panes.
To manage it via FXML, you will have to set a certain property. I can't remember of the top of my head, but I think it is alignment="center"
in your GridPane node.
Upvotes: 3