Joh*_*sen 16 java user-interface resize gridpanel javafx-2
我有一个简单的GridPane显示了几个标签和一个按钮,但我似乎无法让它适合父StackPane.我将如何前进并制作它以填充它所在的任何容器?
GridPane g = new GridPane();
g.add(new Label("Categories"),0,0);
g.add(new Label("Content"),1,0);
Button newCat = new Button("New Category");
newCat.setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent e) {
System.out.println("Clicked");
}
});
g.add(newCat,0,1);
g.setGridLinesVisible(true);
StackPane root = new StackPane();
root.getChildren().add(g);
Scene scene = new Scene(root, 300, 250);
primaryStage.setScene(scene);
primaryStage.show();
Run Code Online (Sandbox Code Playgroud)
UI真的不是我的强项,任何帮助将不胜感激.
Vid*_*del 13
您应该看到此链接,尤其是关于百分比大小调整的部分.如果您只有两列,我发现代码可以工作:
GridPane grid = new GridPane();
/* your code */
ColumnConstraints column1 = new ColumnConstraints();
column1.setPercentWidth(50);
grid.getColumnConstraints().add(column1);
Run Code Online (Sandbox Code Playgroud)
如果有人会寻找答案,这就是它对我有用的方式:
@Override
public void start(Stage stage) throws Exception {
stage.setTitle("Window title");
GridPane grid = new GridPane();
gridSetup(grid); // Building my grid elements here (2 columns)
// Setting columns size in percent
ColumnConstraints column = new ColumnConstraints();
column.setPercentWidth(30);
grid.getColumnConstraints().add(column);
column = new ColumnConstraints();
column.setPercentWidth(70);
grid.getColumnConstraints().add(column);
grid.setPrefSize(WINDOW_WIDTH, WINDOW_HEIGHT); // Default width and height
grid.setMaxSize(Region.USE_COMPUTED_SIZE, Region.USE_COMPUTED_SIZE);
Scene scene = new Scene(grid, WINDOW_WIDTH, WINDOW_HEIGHT);
stage.setScene(scene);
stage.show();
}
Run Code Online (Sandbox Code Playgroud)
通过此设置,网格占据窗口的所有空间并随窗口自动调整大小.
您应该将 GridPane 添加到 HBox 或 VBox 中,而不是将 GridPane 放入 StackPane 中。调整 Gridpane 更加方便。顺便说一句,您仍然有一些方法,例如 g.setPrefSize(arg0, arg1); 相应地设置您的高度和宽度。