问题描述
我正在尝试使用 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",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);
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,20,0));
answerInfoPane.add(datePostedLbl);
answerInfoPane.add(authorLbl);
answerInfoPane.add(stateLbl);
add(answerInfoPane,constraints);
这是使用 GridBagLayout 在较大面板的第二行中添加带有三个 JLabel 的新面板(使用 GridLayout)的结果
最终编辑:我的错。只需要添加一行代码“constraints.fill = GridBagConstraints.BOTH;”。 JPanel 没有使用可用空间,它看起来居中。现在看起来就像我想要的:
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)