gpt4 book ai didi

java - 如何使用 GridBagLayout 消除 Java JTextField 和 JLabel 之间不需要的空间

转载 作者:行者123 更新时间:2023-12-01 09:06:42 25 4
gpt4 key购买 nike

使用 Java GridBagLayout,为什么列之前的第一个 JTextField(标记为 A)右侧有很大的空间,但最后两个 JTextField 的 B 和 C 的行为符合预期,它们之间没有不需要的空格,如何消除该空格?我在下面附上了一张图片来显示问题以及代码。

    /* Label digital timer */
gbcRightPanel.gridx = 0;
gbcRightPanel.gridy = 0;
rightPanel.add(labelDitigalTimer, gbcRightPanel);

/* Text Field Hours */
gbcRightPanel.gridx = 0;
gbcRightPanel.gridy = 1;
gbcRightPanel.weighty = 1;
rightPanel.add(jtxtFieldHours, gbcRightPanel);

/* Label colon */
gbcRightPanel.gridx = 1;
gbcRightPanel.gridy = 1;
rightPanel.add(new JLabel(":"), gbcRightPanel);

/* Text Field Minuites */
gbcRightPanel.gridx = 2;
gbcRightPanel.gridy = 1;
rightPanel.add(jtxtFieldMinuites, gbcRightPanel);

/*Colon*/
gbcRightPanel.gridx = 3;
gbcRightPanel.gridy = 1;
rightPanel.add(new JLabel(":"), gbcRightPanel);

/* Text Field Seconds */
gbcRightPanel.gridx = 4;
gbcRightPanel.gridy = 1;
rightPanel.add(jtxtFieldSeconds, gbcRightPanel);

Image of the right panel with space problem

最佳答案

GridBagLayout 适用于由行/列组成的单元格。

第一行只有一列。第二行有 5 列。

因此,第一列的宽度是第一列所有行中最大组件的宽度,它恰好是您的标签,因此您会看到额外的空间。

改变这种情况的一种方法是让标签占据 5 列。因此,在添加标签之前,您需要使用:

gbcRightPane.gridWidth = 5;
rightPanel.add(labelDitigalTimer, gbcRightPanel);
gbcRightPane.gridWidth = 1; // reset for the other components.

现在标签将出现在所有 5 个组件的上方。然后,您可以通过指定适当的约束来确定标签是居中还是左对齐。

阅读 Swing 教程中关于 How to Use GridBagLayout 的部分有关限制和工作示例的更多信息。

另一种方法是使用嵌套面板。因此,您可以为文本字段和冒号标签创建单独的面板。然后在 GridBagPanel 中添加标签和面板作为两个单独的组件。

阅读教程中的其他布局管理器,了解每个布局管理器的工作原理,以便您可以有效地嵌套面板以获得所需的布局。

关于java - 如何使用 GridBagLayout 消除 Java JTextField 和 JLabel 之间不需要的空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41211826/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com