Unable to Center a Grid Using JavaFX

2019-09-15 06:38发布

问题:

I'm using grid.setAlignment(Pos.CENTER); to center my grid within the JavaFX scene however it doesn't seem to work. The grid always displays in the top left of the scene no matter what position I give it. Can anyone see what I'm doing wrong?

My entire code (minus imports) is as follows:

*public class Main extends Application {
@Override
public void start(Stage stage) throws Exception {
Scene scene = new Scene(new Group(), 450, 250);

Button btn = new Button();
btn.setText("Run");


final ComboBox comboBox = new ComboBox();
comboBox.getItems().addAll(
"Phase 1",
"Phase 2",
"Phase 3",
"Phase 4",
"Phase 5"  
);

GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
grid.setVgap(10);
grid.setHgap(10);
grid.setPadding(new Insets(5, 5, 5, 5));
grid.add(new Label("Select Phase: "), 0, 0);
grid.add(comboBox, 1, 0);
grid.add(new Label("Select Data: "), 0, 1);
grid.add(btn, 0, 2);

Group root = (Group)scene.getRoot();
root.getChildren().add(grid);
stage.setScene(scene);


stage.show();
}*

Thanks!

回答1:

That's not what grid.setAlignment(...) does: it aligns the overall content of the grid pane within the grid pane's bounds (see docs).

The position of the grid pane within its parent is determined by its parent. If you want it centered, use a parent that knows how to center things, such as a StackPane:

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class Main extends Application {
    @Override
    public void start(Stage stage) throws Exception {

        StackPane root = new StackPane();

        Scene scene = new Scene(root, 450, 250);

        Button btn = new Button();
        btn.setText("Run");

        final ComboBox<String> comboBox = new ComboBox<>();
        comboBox.getItems().addAll("Phase 1", "Phase 2", "Phase 3", "Phase 4", "Phase 5");

        GridPane grid = new GridPane();

        grid.setVgap(10);
        grid.setHgap(10);
        grid.setPadding(new Insets(5, 5, 5, 5));
        grid.add(new Label("Select Phase: "), 0, 0);
        grid.add(comboBox, 1, 0);
        grid.add(new Label("Select Data: "), 0, 1);
        grid.add(btn, 0, 2);


        root.getChildren().add(grid);
        stage.setScene(scene);

        stage.show();
    }

    public static void main(String[] args) { launch(args);}
}