【问题标题】:JavaFX GridPane - Configuring controls to grow and occupy all the available spaceJavaFX GridPane - 配置控件以增长并占用所有可用空间
【发布时间】:2016-11-30 12:51:41
【问题描述】:

努力实现:

  1. Text Field 1 和 Text Field 3 应该占用所有可用空间
  2. Button 1 和 Button 2 应该具有相同的宽度

问题:

Text Field 1 和 Text Field 3 并没有占用所有可用空间(尽管一旦 Label 完全显示它们就会增长)

这是屏幕截图:

// Removed imports for brevity

public class GridPaneTest extends Application
{
  @Override
  public void start(Stage primaryStage)
  {
    primaryStage.setTitle("GridPane Test");

    GridPane gridPane = new GridPane();
    // gridPane.setGridLinesVisible(true);
    gridPane.setHgap(5);
    gridPane.setVgap(5);
    gridPane.setPadding(new Insets(5));

    TextField tf1 = new TextField("Text Field 1");
    GridPane.setHgrow(tf1, Priority.ALWAYS);
    gridPane.add(tf1, 0, 0);
    TextField tf2 = new TextField("Text Field 2");
    GridPane.setHgrow(tf2, Priority.NEVER);
    gridPane.add(tf2, 1, 0);
    Button button1 = new Button("Button 1");
    button1.setMaxWidth(140);
    GridPane.setHgrow(button1, Priority.NEVER);
    GridPane.setHalignment(button1, HPos.RIGHT);
    gridPane.add(button1, 2, 0);

    TextField tf3 = new TextField("Text Field 3");
    GridPane.setHgrow(tf3, Priority.ALWAYS);
    gridPane.add(tf3, 0, 1, 2, 1);
    Button button2 = new Button("Button 2 Button 2");
    button2.setMaxWidth(140);
    GridPane.setHgrow(button2, Priority.NEVER);
    GridPane.setHalignment(button2, HPos.RIGHT);
    gridPane.add(button2, 2, 1);

    Label label1 = new Label(
        "Label 1 Label 1 Label 1 Label 1 Label 1 Label 1 Label 1 Label 1 Label 1 Label 1 Label 1");
    GridPane.setHgrow(label1, Priority.ALWAYS);
    gridPane.add(label1, 0, 2, 3, 1);

    primaryStage.setScene(new Scene(gridPane)); 

    primaryStage.show();
  }

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

【问题讨论】:

    标签: java layout javafx-8 gridpane


    【解决方案1】:

    根据GridPane documentation

    如果应用程序需要显式控制行或列的大小,它可以通过添加 RowConstraints 和 ColumnConstraints 对象来指定这些指标

    gridPane.getColumnConstraints()
      .addAll(new ColumnConstraints(), new ColumnConstraints(),
        new ColumnConstraints(140) /* Control the third column size */);
    

    屏幕截图:

    【讨论】:

    • 现在按钮宽度可以设置为Button.setMaxWidth(Double.MAX_VALUE) - 两个按钮大小相同。
    猜你喜欢
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    • 2016-07-15
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    • 2020-11-03
    • 2014-01-05
    相关资源
    最近更新 更多