JPanel GridBagLayout到GridPane

时间:2016-09-09 14:41:45

标签: java swing user-interface javafx

我目前正在尝试将应用程序迁移到JavaFX(它实际上部分使用AWT)并且将边界布局的JPanel切换到BorderPanes相当容易,我在如何解决如何使用GridBagLayout和GridPanes。 (我以前从未在Swing中使用过此布局)
在我的代码中,GridBagLayout使用了2次(我不确定这是否是自动生成的代码):

JPanel bottomMessagePanel = new JPanel();
bottomMessagePanel.setLayout(new GridBagLayout());
bottomMessagePanel.setBorder(BorderFactory.createEmptyBorder());
bottomMessagePanel.add(someJComponent, new GridBagConstraints(0, 0, 1, 1, .35, 1, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
bottomMessagePanel.add(someOtherJComponent, new GridBagConstraints(1, 0, 1, 1, .65, 1, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));

JPanel stepPanel = new JPanel();
stepPanel.setLayout(new GridBagLayout());
stepPanel.add(someJComponent, new GridBagConstraints(1, 0, 1, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
stepPanel.add(someOtherJComponent, new GridBagConstraints(0, 0, 1, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
stepPanel.add(some3rdJComponent, new GridBagConstraints(2, 0, 1, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));

如何使用JavaFX GridPane执行此操作? 不要担心转换那些JComponents,因为我已经转换了那些......

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:5)

指定将值传递给构造函数的GridBagConstraints

GridBagConstraints(
        int gridx,
        int gridy,
        int gridwidth,
        int gridheight,
        double weightx,
        double weighty,
        int anchor,
        int fill,
        Insets insets,
        int ipadx,
        int ipady)

让我们来描述如何在JavaFX中使用这些参数的等价物:

Node node = ...
GridPane gridPane = ...

gridx,gridy,gridwidth,gridheight

通常您使用add的{​​{1}}方法来指定这些值。它们在JavaFX中称为GridPanecolumnIndexrowIndexcolumnSpan。如果rowSpancolumnSpan为1,则只需使用rowSpan方法获取3个参数:

add

如果其中一个gridPane.add(node, gridx, gridy); / columnSpan更大,您可以使用该方法的重载版本:

rowSpan

weightx,重量

那些没有直接的等价物。相反,您需要使用ColumnConstraintsRowConstraintsgridPane.add(node, gridx, gridy, gridwidth, gridheight); percentWidth为整行/列定义此内容(除非您是&#39} ;对标准布局感到满意。)

行和列约束已添加到columnConstraintsrowConstraints列表中。

您可以使用percentHeight / halignment的{​​{1}} / valignment属性,或使用ColumnConstrants和{{为单个节点指定此属性1}}:

RowConstraints

相当于使用GridPane.setHalignmentGridPane.setValignment为单个节点设置行和列约束的GridPane.setHalignment(node, HPos.LEFT); GridPane.setValignment(node, VPos.TOP); fillHeight值:

fillWidth

这些属性的默认值为GridPane.setFillWidth

插图

您可以使用GridPane.setFillHeight指定此项。如果您对所有值使用GridPane.setFillWidth(node, Boolean.FALSE); GridPane.setFillHeight(node, Boolean.FALSE); ,则无需指定此值。

true

ipadx,ipady

JavaFX中没有相同的内容。

GridPane.setMargin 0方法允许您一次设置多个约束,例如

setConstraints(Node child, int columnIndex, int rowIndex, int columnspan, int rowspan, HPos halignment, VPos valignment, Priority hgrow, Priority vgrow, Insets margin)