gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:15:08 25 4
gpt4 key购买 nike

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

有人可以向我解释如何根据我的要求更改它吗?

最佳答案

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

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

那个虚拟的 JLabel 将占据您的项目 JLabel 下的所有空间。

enter image description here

关于java - 在Java Swing中设置GridBagLayout在JPanel顶部的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22604053/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com