You can use next trick: add next code after your loop:
gridBagConstraints.weighty=1;
gridBagConstraints.gridy++;
pnlProjects.add(new JLabel(" "), gridBagConstraints);
That dummy JLabel
will grab all space under your project JLabel
's.
Domanda
I have written the following code to add a JLabel
to a JPanel
but it displays it in the center, while I expected it to be placed at the top of the JPanel
.
Here is the piece of code I'm referring to:
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);
Would anyone be ablt to explain to me how to change it as per my requirement?
Soluzione
You can use next trick: add next code after your loop:
gridBagConstraints.weighty=1;
gridBagConstraints.gridy++;
pnlProjects.add(new JLabel(" "), gridBagConstraints);
That dummy JLabel
will grab all space under your project JLabel
's.