java - 在 JPanel 上正确设置 GridBagLayout 约束
问题描述
我正在尝试使用 GridBagLayout 手动编写程序的一部分。我试图让前两个组件底部的三个 JLabel 大小相同,但是,如您所见,“dd/mm/yyyy”和“author”标签比“State”更接近。
你可以在这里看到它的样子:
这是我迄今为止为获得上述结果所做的一些代码。
JButton btn;
VotesView votesView = new VotesView();
JScrollPane contentScrollPane = new JScrollPane();
JTextArea contentTxtArea = new JTextArea();
JLabel datePostedLbl = new JLabel("dd/mm/yyyy", JLabel.CENTER);
JLabel authorLbl = new JLabel("Author", JLabel.CENTER);
JLabel stateLbl = new JLabel("State", JLabel.CENTER);
/* add "Votes" (custom panel class) */
constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 0;
constraints.gridy = 0;
add(votesView, constraints);
/* add JTextArea */
constraints = new GridBagConstraints();
contentTxtArea.setMargin(new Insets(3,7,3,7));
contentScrollPane.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
contentTxtArea.setEditable(true);
contentTxtArea.setColumns(20);
contentTxtArea.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
contentTxtArea.setLineWrap(true);
contentTxtArea.setRows(4);
contentTxtArea.setText("Contenido");
contentScrollPane.setViewportView(contentTxtArea);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridwidth = 2;
constraints.gridx = 1;
constraints.gridy = 0;
constraints.weightx = 1; // el texto de la respuesta tiene mas espacio en el panel
add(contentScrollPane, constraints);
/* add dd/mm/yyyy Label */
constraints = new GridBagConstraints();
//constraints.insets = new Insets(10,10,10,10);
constraints.gridx = 0;
constraints.gridy = 1;
add(datePostedLbl, constraints);
/* add Author JLabel */
constraints.gridx = 1;
constraints.gridy = 1;
add(authorLbl, constraints);
/* add State JLabel */
constraints.gridx = 2;
constraints.gridy = 1;
add(stateLbl, constraints);
任何人都可以帮助我让三个底部的 JLabel 对齐吗?
编辑:好的。我在一个新的 JPanel 上使用了一个网格布局来拥有三列和一行,但是 dateLbl 在最后放置了一个“...”。我是否应该设置 JLabels 的大小(我需要完全显示日期)?我在标签之间使用了 20 的水平间隙。
constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 1;
constraints.gridwidth = 2;
JPanel answerInfoPane = new JPanel();
answerInfoPane.setLayout(new GridLayout(1, 3, 20, 0));
answerInfoPane.add(datePostedLbl);
answerInfoPane.add(authorLbl);
answerInfoPane.add(stateLbl);
add(answerInfoPane, constraints);
这是使用 GridBagLayout 在较大面板的第二行添加三个 JLabel 的新面板(使用 GridLayout)的结果
最后编辑:我的错。只需添加代码行“constraints.fill = GridBagConstraints.BOTH;”。JPanel 没有使用可用空间,它看起来居中。现在看起来就像我想要的:
解决方案
推荐阅读
- python - ValueError:重复可能不包含负值
- javascript - 重复反应组件的最佳实践
- r - R 从下一个不相等的值中进行条件减法
- hibernate - 批量更新并返回 JPA/Hibernate 中失败更新的 Id
- swift - 在swiftui,ios14中触摸本地通知时重定向到工作表或演示文稿
- javascript - 使用 Javascript for Automation (JXA) 从 Apple Numbers 中的单元格选择中获取表名
- junit - Apache Camel:文件和 http 组件的单元测试
- python - ImportError:无法从“sqlalchemy”导入名称“事件”
- bash - 执行 ksh 脚本不会继承环境变量
- laravel - 如何跳过对空数组的验证?