问题
For some reason, JavaFX's ToolBar
only proposes two options for items alignment: LEFT_TO_RIGHT
and RIGHT_TO_LEFT
.
And funnily enough, if this is RIGHT_TO_LEFT
you have to specify your items in reverse order so that they show up naturally...
However I don't see any option for aligning elements in the center. How do you achieve that? Or must I use something else than a toolbar?
edit: here is the current code... Unfortunately this doesn't work :(
FXML:
<BorderPane xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1"
fx:controller="com.github.fge.grappa.debugger.csvtrace.tabs.linechart.LineChartTabDisplay">
<top>
<ToolBar fx:id="toolbar">
<HBox fx:id="hbox" alignment="CENTER">
<Region fx:id="leftSpacer"/>
<Button text="Refresh"/>
<ProgressBar visible="false"/>
<Label text="Layout testing"/>
<Region fx:id="rightSpacer"/>
</HBox>
</ToolBar>
</top>
</BorderPane>
the class:
public class LineChartTabDisplay
extends JavafxDisplay<LineChartTabPresenter>
{
public Region leftSpacer;
public Region rightSpacer;
public ToolBar toolbar;
public HBox hbox;
@Override
public void init()
{
HBox.setHgrow(leftSpacer, Priority.SOMETIMES);
leftSpacer.setMinWidth(Region.USE_PREF_SIZE);
HBox.setHgrow(rightSpacer, Priority.SOMETIMES);
rightSpacer.setMinWidth(Region.USE_PREF_SIZE);
}
}
But this is what it gives:

回答1:
FOUND.
In fact, the code is pretty "simple". Kind of, since this really should be in the ToolBar
for starters, but here goes...
The FXML is now as follows:
<BorderPane xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1"
fx:controller="com.github.fge.grappa.debugger.csvtrace.tabs.linechart.LineChartTabDisplay">
<top>
<ToolBar fx:id="toolbar">
<HBox fx:id="hbox" alignment="CENTER" spacing="5.0">
<Button text="Refresh"/>
<Label text="Layout testing"/>
</HBox>
</ToolBar>
</top>
</BorderPane>
And the code is simply:
public class LineChartTabDisplay
extends JavafxDisplay<LineChartTabPresenter>
{
@FXML
protected ToolBar toolbar;
@FXML
protected HBox hbox;
@Override
public void init()
{
hbox.minWidthProperty().bind(toolbar.widthProperty());
}
}
回答2:
Well there is this little hack to produce a dynamic spacer:
final Region spacer = new Region();
HBox.setHgrow(spacer, Priority.SOMETIMES);
spacer.setMinWidth(Region.USE_PREF_SIZE);
If you put one as first item and another one as last item on the ToolBar
your items inbetween should be centered.
回答3:
Just keep an eye on the width of the Toolbar and apply the new value to the HBox. This is necessary in order to monitor the size of the Stage
toolbar.widthProperty().addListener((obs, oldVal, newVal) -> {
hbox.setPrefWidth(newVal.doubleValue());
});
来源:https://stackoverflow.com/questions/28383821/how-do-you-specify-that-you-want-your-elements-in-a-toolbar-to-be-centered