I have a JPanel containing a gridbaglayout which I would like to align to the left side of my panel. When I write the code to anchor my labels to
the left it still does not work. I have indeed done some research and ask this question somewhere else but the help I received did not fix my problem.
This class extends the JPanel
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
public class Panel extends JPanel{
JLabel field[] = new JLabel[60];
public Panel()
{
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx=0;
c.gridy=0;
c.anchor = GridBagConstraints.WEST; //Align to the left?
setBackground(Color.red);
for(int i=0;i<field.length;i++)
{
field[i] = new JLabel("Test"); // Initialize labels
field[i].setText("Field["+(i+1)+"]");
add(field[i], c);
if(c.gridx== 2) // if 3 colums are made go to next row and start colums from 0
{
c.gridx= 0;
c.gridy++;
}
else
{
c.gridx++;
}
}
}
}


Sign In
Create Account


Back to top










