无法使用JavaFX使网格居中 [英] Unable to Center a Grid Using JavaFX
问题描述
我正在使用 grid.setAlignment(Pos.CENTER); 将我的网格集中在JavaFX场景中,但它似乎不起作用。无论我给出什么位置,网格总是显示在场景的左上角。谁能看到我做错了什么?
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();
}*
谢谢!
推荐答案
这不是 grid.setAlignment(...)
的作用:它对齐网格中网格窗格的整体内容窗格的界限(参见 docs )。
That's not what grid.setAlignment(...)
does: it aligns the overall content of the grid pane within the grid pane's bounds (see docs).
网格窗格在其父级内的位置由其父级确定。如果您希望它居中,请使用知道如何居中的父级,例如 StackPane
:
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);}
}
这篇关于无法使用JavaFX使网格居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!