我编写了以下代码,将JLabel
添加到JPanel
,但它会将其显示在中心,而我预计它会放在JPanel
的顶部。
以下是我所指的代码:
JPanel pnlProjects = new JPanel();
pnlProjects.setMinimumSize(new Dimension(10, 300));
GridBagLayout gridBagLayout = new GridBagLayout();
pnlProjects.setLayout(gridBagLayout);
GridBagConstraints gridBagConstraints = new GridBagConstraints();
// add multiple label dynamically;
for (int count = 0; count < project.length; count++) {
lblProjects[count] = new JLabel("Project"+count );
lblProjects[count].setHorizontalAlignment(SwingConstants.LEFT);
lblProjects[count].setHorizontalTextPosition(SwingConstants.LEFT);
lblProjects[count].setBorder(BorderFactory.createBevelBorder(0));
lblProjects[count].setPreferredSize(new Dimension(100, 20));
gridBagConstraints.fill = GridBagConstraints.VERTICAL;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = count;
pnlProjects.add(lblProjects[count], gridBagConstraints);
}
// Add project panel in to the scorllPan
JScrollPane jspProjectlist = new JScrollPane(pnlProjects);
有人会根据我的要求向我解释如何改变它吗?
答案 0 :(得分:5)
您可以使用下一个技巧:在循环后添加下一个代码:
gridBagConstraints.weighty=1;
gridBagConstraints.gridy++;
pnlProjects.add(new JLabel(" "), gridBagConstraints);
虚拟JLabel
将获取项目JLabel
下的所有空间。