【问题标题】:Setting the position of GridBagLayout at the top of JPanel in Java Swing在 Java Swing 中设置 GridBagLayout 在 JPanel 顶部的位置
【发布时间】:2014-05-01 11:51:18
【问题描述】:

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

谁能根据我的要求向我解释如何更改它?

【问题讨论】:

    标签: java swing user-interface layout gridbaglayout


    【解决方案1】:

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

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

    那个虚拟的JLabel 会占用你项目JLabel 下的所有空间。

    【讨论】:

    • 感谢您提供如此完美的答案,这是正确的方式吗?
    • 这是GridBagLayout特有的,我总是使用虚拟组件来抓取空白空间。
    猜你喜欢
    • 2018-02-24
    • 1970-01-01
    • 1970-01-01
    • 2013-09-01
    • 2023-01-15
    • 2015-12-02
    • 2015-08-11
    • 1970-01-01
    • 2015-08-21
    相关资源
    最近更新 更多