Issue
I have a HBox
inside a VBox
and while most questions seem to be asking how to get the HBox
to use the whole width of the VBox
it is contained in, I require the opposite. I have buttons inside the HBox
which constantly vary in amount, thus the HBox
should continually alter it's size, but after adding a background colour to the HBox
it's clear it occupies the entire width of the VBox
, making centring it impossible.
It's currently like the top example, but I need it to be like the bottom example:
And using
HBox.setHgrow(wordButtonsBox, Priority.NEVER);
doesn't change anything either..
public class CentreStuff extends Application {
@Override
public void start(Stage primaryStage) {
primaryStage.setScene(new Scene(createContent()));
primaryStage.show();
}
private Region createContent() {
HBox buttonBox1 = new HBox(new Button("Button1"), new Button("Button2"), new Button("Button3"), new Button("Button4"));
buttonBox1.setStyle("-fx-border-color: red;");
VBox results = new VBox(10, buttonBox1);
return results;
}
Solution
There are two ways, with slightly different effects depending on what else is in the VBox
:
-
will attempt to resize all the VBox's content to its preferred width, regardless of the width of theresults.setFillWidth(false);
VBox
. Setting it totrue
(the default) will size theVBox
's content to the width of theVBox
, if possible. -
will prevent thebuttonBox1.setMaxWidth(Region.USE_PREF_WIDTH);
HBox
from being wider than its preferred width, so this will keep theHBox
at its preferred width. This solution will allow other components in theVBox
to be sized to the width of theVBox
, if that's what you need.
public class CentreStuff extends Application {
@Override
public void start(Stage primaryStage) {
primaryStage.setScene(new Scene(createContent()));
primaryStage.show();
}
private Region createContent() {
HBox buttonBox1 = new HBox(new Button("Button1"), new Button("Button2"), new Button("Button3"), new Button("Button4"));
buttonBox1.setStyle("-fx-border-color: red;");
VBox results = new VBox(10, buttonBox1);
results.setFillWidth(false);
return results;
}
}
or
public class CentreStuff extends Application {
@Override
public void start(Stage primaryStage) {
primaryStage.setScene(new Scene(createContent()));
primaryStage.show();
}
private Region createContent() {
HBox buttonBox1 = new HBox(new Button("Button1"), new Button("Button2"), new Button("Button3"), new Button("Button4"));
buttonBox1.setStyle("-fx-border-color: red;");
buttonBox1.setMaxWidth(Region.USE_PREF_SIZE);
VBox results = new VBox(10, buttonBox1);
return results;
}
}
Answered By - James_D
Answer Checked By - Marie Seifert (JavaFixing Admin)