【问题标题】:JavaFX: Organize controls in rows (in gridpane) using FXMLJavaFX:使用 FXML 按行(在网格窗格中)组织控件
【发布时间】:2016-05-26 14:59:02
【问题描述】:

我有一个带有很多控件(标签、文本字段、组合框和复选框)的 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,这几乎是我想要的,但我希望将元素放在具有固定宽度的列中。

【问题讨论】:

  • 虽然我没有回答你的问题,但你考虑过使用SceneBuilder吗?
  • 感谢您的建议。事实上,我已经尝试过了,但发现它对于很多元素来说太慢了。此外,处理有时非常困难。但它可能有助于对行重新编号

标签: javafx fxml gridpane


【解决方案1】:

您可以使用对象来跟踪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 开发。在互联网上大量阅读后,我发现没有合适的解决方案,但这在这里可以工作。我会接受你的回答,因为这听起来最有希望。谢谢,如果我再次使用 JavaFX 开发,我会考虑它:)
  • 它可以工作,但不要忘记添加 RowCounter 的导入 :)
猜你喜欢
  • 2014-04-09
  • 2021-03-27
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多