在Java Swing中将GridBagLayout的位置设置在JPanel的顶部

时间:2014-03-24 08:12:34

标签: java swing user-interface layout gridbaglayout

我编写了以下代码,将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);

enter image description here

有人会根据我的要求向我解释如何改变它吗?

1 个答案:

答案 0 :(得分:5)

您可以使用下一个技巧:在循环后添加下一个代码:

gridBagConstraints.weighty=1;
gridBagConstraints.gridy++;
pnlProjects.add(new JLabel(" "), gridBagConstraints);

虚拟JLabel将获取项目JLabel下的所有空间。

enter image description here