JavaFX View:add 和 setConstraint 之间有区别吗?



add((或setConstraint之间有区别吗,所以是的,是什么,偏好还是真的有很大的区别?

public class example extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("Example");
GridPane grid = new GridPane();
Label label = new Label("Example A");
Label label2 = new Label("Example B");
grid.add(label, 0,0);
GridPane.setConstraints(label2, 1, 0);
grid.getChildren().add(label2);
Scene scene = new Scene(grid, 300,200);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
} 

GridPane类中两种方法的实现:

/**
* Adds a child to the gridpane at the specified column,row position.
* This convenience method will set the gridpane column and row constraints
* on the child.
* @param child the node being added to the gridpane
* @param columnIndex the column index position for the child within the gridpane, counting from 0
* @param rowIndex the row index position for the child within the gridpane, counting from 0
*/
public void add(Node child, int columnIndex, int rowIndex) {
setConstraints(child, columnIndex, rowIndex);
getChildren().add(child);
}
/**
* Sets the column,row indeces for the child when contained in a gridpane.
* @param child the child node of a gridpane
* @param columnIndex the column index position for the child
* @param rowIndex the row index position for the child
*/
public static void setConstraints(Node child, int columnIndex, int rowIndex) {
setRowIndex(child, rowIndex);
setColumnIndex(child, columnIndex);
}

add方法将子项添加到网格窗格的指定列、行位置。setConstraints设置包含在网格窗格中时子项的列、行。

setConstraints不会添加子项,但指定子项在GridPane中的显示方式。

tl;博士

add添加一个节点并设置其约束,而setConstraints只为之前已添加到GridPaneNode设置约束。

来自GridPane的 JavaDocs :

public void add(Node child,
int columnIndex,
int rowIndex)

子项添加到网格窗格中的指定列、行位置。这种方便的方法将在子项上设置网格窗格列和行约束。

参数:
child - 要添加到网格窗格中的节点

columnIndex - 子项在网格窗格中的列索引位置,从 0
rowIndex - 子项在网格窗格中的行索引位置,从 0 开始计数

这意味着传递的Node将被添加,并将根据给定的约束进行对齐。

<小时 />
public static void setConstraints(Node child,
int columnIndex,
int rowIndex,
int columnspan,
int rowspan)

设置包含在网格窗格中的子项的列、行、列范围和行跨度值。

参数:
子节点 - 网格窗格的子节点
columnIndex - 子节点的列索引位置
rowIndex - 子项的行索引位置

列跨度 - 子项应跨越的列数
行跨度- 子项应跨越的行数

虽然这意味着您可以设置已经是GridPane子级或以后可能添加到子级Node的约束,但此方法从不添加Node本身。

我想你在这里把事情搞混了? setConstraint(( 将布局设置为子对象约束,而 add(( 只是将子对象添加到父对象。

最新更新