![](/img/trans.png)
[英]Java Swing's GridBagLayout will not position component at the top of the grid cell
[英]Setting the position of GridBagLayout at the top of JPanel in Java Swing
我編寫了以下代碼,將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);
有人願意向我解釋如何根據我的要求進行更改嗎?
您可以使用下一個技巧:在循環之后添加下一個代碼:
gridBagConstraints.weighty=1;
gridBagConstraints.gridy++;
pnlProjects.add(new JLabel(" "), gridBagConstraints);
那個虛假的JLabel
將搶占項目JLabel
的所有空間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.