我们需要一个具有以下要求的3列布局解决方案:
假设我们有一个440px的水平空间和一个固定大小为40px的中间列。另外两列应该共享剩余的400px,这样每列的宽度为200px。
------------------------------------
| 200px | 40px | 200px |
------------------------------------
如果整体尺寸发生变化,让我们说500px,中间列的宽度不应该改变,但其他的应该改变。
----------------------------------------
| 230px | 40px | 230px |
----------------------------------------
如果可以使用GridPane,请告诉我如何。
如果使用GridPane无法做到这一点,我会打开其他建议。
我更喜欢简单的解决方案a)没有FXML的Java代码和b)仅JavaFx,所以额外的库。
答案 0 :(得分:4)
您只需要三个列约束:
ColumnConstraints leftCol = new ColumnConstraints();
leftCol.setHgrow(Priority.ALWAYS);
ColumnConstraints middleCol = new ColumnConstraints(40);
ColumnConstraints rightCol = new ColumnConstraints();
rightCol.setHgrow(Priority.ALWAYS);
GridPane gridPane = new GridPane();
gridPane.getColumnConstraints().addAll(leftCol, middleCol, rightCol);
如果您愿意,可以在FXML中执行相同操作:
<GridPane>
<columnConstraints>
<ColumnConstraints hgrow="ALWAYS"/>
<ColumnConstraints minWidth="40" prefWidth="40" maxWidth="40"/>
<ColumnConstraints hgrow="ALWAYS"/>
</columnConstraints>
<!-- ... -->
</GridPane>
这是一个SSCCE:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.stage.Stage;
public class GridPaneTest extends Application {
@Override
public void start(Stage primaryStage) {
ColumnConstraints leftCol = new ColumnConstraints();
leftCol.setHgrow(Priority.ALWAYS);
ColumnConstraints middleCol = new ColumnConstraints(40);
ColumnConstraints rightCol = new ColumnConstraints();
rightCol.setHgrow(Priority.ALWAYS);
GridPane gridPane = new GridPane();
gridPane.getColumnConstraints().addAll(leftCol, middleCol, rightCol);
Region left = new Region();
left.setMinHeight(80);
left.setStyle("-fx-background-color: red;");
Region middle = new Region();
middle.setMinHeight(80);
middle.setStyle("-fx-background-color: green ;");
Region right = new Region();
right.setMinHeight(80);
right.setStyle("-fx-background-color: blue ;");
gridPane.addRow(0, left, middle, right);
Scene scene = new Scene(gridPane, 400, 80);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}