JLabel won't left-align
I've got a JPanel with a GridBagLayout as its layout manager. I'm trying to add a JLabel to it and I want it pushed all the way to the left side. Here's my code:
The JLabel doesn't seem to want to left align. It's always centered.
JPanel SouthPanel = new JPanel(new GridBagLayout());
SouthPanel.setPreferredSize(new Dimension(400, 50));
ClockJLabel CL = new ClockJLabel();
GridBagConstraints GBC = new GridBagConstraints();
GBC.gridx = GBC.gridy = 0;
GBC.anchor = GridBagConstraints.LINE_START;
Can anyone see what the problem might be?
Is that the only component being added to the SouthPanel? If so, why use GridbagLayout and not BorderLayout placing the label in the BorderLayout.WEST position?
I also suggest that if this doesn't help you, you create and post an SSCCE to allow us to see for ourselves what the problem may be. You also should read up on Java naming conventions (class names begin with a capital letter and variable and method names begin lower case) since following this will make your code easier for us to understand and thus make it easier for us to help you.
You need to set a non-zero weightx so the layout knows how to distribute extra space.
Originally Posted by Darryl.Burke
Adding GBC.weightx = 1 fixed the problem.
Thanks for the suggestions. I'm using the GridBagLayout because it's the only layout manager I know of that keeps components at their preferred size (though I don't know all the layout managers inside and out).
I'm also going to add conforming-to-Java-naming-conventions to my list of tasks. Also, if I were to post a SSCCE, would it suffice to upload my program in a zip file as an attachment to my post (of course, not the whole program as it stands, but a minimal version that is both compilable and demonstrates the problem I'm dealing with)?
If you make a decent SSCCE, then it should be small enough to post the code directly in the forum using code tags.
Glad you have fixed your problem!