我有一个带有很多控件(标签、文本字段、组合框和复选框)的 GUI。我将它们组织在一个 Gridpane 中,并希望它们以行和列的形式排列(就像它与 gridpane 布局一样)。
如果我使用 FXML,我会这样写:
<GridPane>
<Label GridPane.rowIndex="0" GridPane.columnIndex="0" text="field1"/>
<TextField GridPane.rowIndex="0" GridPane.columnIndex="1"/>
<Label GridPane.rowIndex="1" GridPane.columnIndex="0" text="field2"/>
<TextField GridPane.rowIndex="1" GridPane.columnIndex="1"/>
</GridPane>
现在的问题是:如果我想在第 0 行和第 1 行之间添加一行,我需要增加下一行的行索引。现在让我们取 20 行和 5 列,我想在第一行之后添加一行。这将为我增加第一行下方每一行的行号提供很大的负担。
是否有类似行元素的东西将其子控件放置在同一行中且列数增加?我想到了这样的事情:
<GridPane>
<GridPane.Row>
<Label text="field1"/>
<TextField/>
</GridPane.Row>
<GridPane.Row>
<Label text="field2"/>
<TextField/>
</GridPane.Row>
</GridPane>
我确实知道 VBox 和 HBox,这正是我想要的,但我希望元素在列中具有固定宽度。
最佳答案
您可以使用一个对象来跟踪rowIndex
。
Java:
public class RowCounter {
private int currentRowIndex = 0;
/**
* Return current rowIndex.
* @return
*/
public int getCr() {
return currentRowIndex;
}
/**
* Return current rowIndex and increase it.
* @return
*/
public int getNr() {
return currentRowIndex++;
}
}
FXML:
<GridPane xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
<fx:define>
<RowCounter fx:id="rc" />
</fx:define>
<children>
<Label text="Name:" GridPane.columnIndex="0" GridPane.rowIndex="$rc.cr" />
<TextField GridPane.columnIndex="1" GridPane.rowIndex="$rc.nr" />
<Label text="Age:" GridPane.columnIndex="0" GridPane.rowIndex="$rc.cr" />
<TextField GridPane.columnIndex="1" GridPane.rowIndex="$rc.nr" />
<Label text="Address:" GridPane.columnIndex="0" GridPane.rowIndex="$rc.cr" />
<TextField GridPane.columnIndex="1" GridPane.rowIndex="$rc.nr" />
</children>
</GridPane>
关于JavaFX:使用 FXML 按行(在网格 Pane 中)组织控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35413791/