簡體   English   中英

在Java Swing的JPanel頂部設置GridBagLayout的位置

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM