+1 @JamesD 的建议和@Oboe 的回答。理想情况下,我会分离每一行布局,以便以简单的方式处理它,而不是仅使用一个 GridPane 使其变得复杂。
话虽如此,如果您想了解或了解如何使用一个 GridPane 进行类似的布局,下面的实现可能会给您一个快速的想法。
首先将您的布局拆分为所需的列,以确定您需要多少列。 (如下图)
现在您将知道哪个节点将位于哪个列以及它将占据多少列(colspan)
我将针对一个节点进行解释:
假设您要插入名字的字段。如果你注意到图片中,它在rowIndex:0,columnIndex:1,它占据了4列,所以colSpan的值为4。这里我们没有合并任何行,所以rowSpan的值总是1。
pane.add(getField(), 1, 0, 4, 1); // node, colIndex, rowIndex, colSpan, rowSpan
同样,您可以关联其余的节点布局。而且为了更精确,您可以使用 ColumnConstraints 设置每列的首选宽度。下面是布局和约束的完整代码:
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class CreditCardPaneDemo extends Application {
@Override
public void start(Stage stage) throws Exception {
VBox root = new VBox();
root.setPadding(new Insets(5));
root.setSpacing(10);
Scene scene = new Scene(root,300,200);
stage.setScene(scene);
stage.setTitle("CreditCard");
stage.show();
GridPane pane = new GridPane();
pane.setStyle("-fx-border-color:black;-fx-border-width:1px;-fx-background-color:yellow");
pane.setPadding(new Insets(5));
pane.setHgap(5);
pane.setVgap(5);
pane.add(getLabel("First"), 0, 0, 1, 1);
pane.add(getField(), 1, 0, 4, 1);
pane.add(getLabel("Last"), 5, 0, 1, 1);
pane.add(getField(), 6, 0, 2, 1);
pane.add(getLabel("Card Number"), 0, 1, 3, 1);
pane.add(getField(), 3, 1, 5, 1);
pane.add(getLabel("Month"), 0, 2, 2, 1);
pane.add(getField(), 2, 2, 2, 1);
pane.add(getLabel("Year"), 4, 2, 1, 1);
pane.add(getField(), 5, 2, 1, 1);
pane.add(getLabel("CVV"), 6, 2, 1, 1);
pane.add(getField(), 7, 2, 1, 1);
pane.getColumnConstraints().addAll(getCc(70), getCc(20), getCc(80), getCc(20), getCc(25), getCc(90), getCc(80), getCc(100));
CheckBox gridLines = new CheckBox("Show grid lines");
gridLines.selectedProperty().addListener((obs, old, val) -> pane.gridLinesVisibleProperty().set(val));
root.getChildren().addAll(gridLines, pane);
}
private ColumnConstraints getCc(double width) {
ColumnConstraints cc = new ColumnConstraints();
cc.setPrefWidth(width);
return cc;
}
private Label getLabel(String txt) {
Label lbl = new Label(txt);
lbl.setMinWidth(Region.USE_PREF_SIZE);
return lbl;
}
private TextField getField() {
TextField field = new TextField();
field.setMaxWidth(Double.MAX_VALUE);
return field;
}
}