Reputation: 2166
The label does not align to the left of the center layout. If the GridLayout
is not present, then it moves correctly. Is there a way to do it to move JLabel to the extreme left?
I've tried setHorizontalAlignment and setAlignmentX and both did not work
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class asd {
public static void main(String[] args){
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
JLabel lab = new JLabel("LABEL",SwingConstants.LEFT);
//lab.setHorizontalAlignment(SwingConstants.CENTER);
GridLayout grid = new GridLayout(3,3,2,1);
JPanel yourGrid = new JPanel(grid);
panel.add(lab);
for(int i=0; i<3; i++){
for(int j=0; j<3; j++){
JButton but = new JButton();
yourGrid.add(but);
}
}
panel.add(yourGrid);
frame.getContentPane().add(BorderLayout.CENTER,panel);
frame.setVisible(true);
frame.pack();
}
}
Upvotes: 2
Views: 12068
Reputation: 9038
When using BoxLayout you have to set the alignment for any of the elements inside.
As this example follows: http://docs.oracle.com/javase/tutorial/uiswing/layout/box.html
Fixing Alignment Problems
You have to set alignment to your lab and yourGrid
lab.setHorizontalAlignment(SwingConstants.LEFT);
yourGrid.setAlignmentX(Component.LEFT_ALIGNMENT);
Upvotes: 7