Water Cooler v2 Water Cooler v2 -4 years ago 278
Java Question

How do I left align a JLabel inside a JPanel?

I am trying to build a status bar for my login dialog box but the label doesn't align to the left of the status panel. Here is my code.

public class LoginDialog extends JDialog {

private static final long serialVersionUID = 1L;

protected JLabel lblTopSpace = null;
protected JPanel loginPanel = null;
protected JPanel statusPanel = null;

public LoginDialog(String title) {




protected void Initialize() {

lblTopSpace = new JLabel("Login into Bookyard");

loginPanel = new LoginPanel();
statusPanel = new JPanel();

statusPanel.setBorder(new BevelBorder(BevelBorder.LOWERED));
statusPanel.setSize(this.getWidth(), 50);

JLabel lblStatus = new JLabel("Status");
lblStatus.setFont(new Font("Verdana", Font.PLAIN, 12));

this.setLayout(new BorderLayout());
Container container = this.getContentPane();

container.add(lblTopSpace, BorderLayout.NORTH);
container.add(loginPanel, BorderLayout.CENTER);
container.add(statusPanel, BorderLayout.SOUTH);


Here is what it looks like presently.

enter image description here

What am I missing?

Answer Source

Your label is inside a panel that is inside the contentpane of the dialog. So the label is managed with the layout of its parent panel. But you don't set any particular layout for it, then it's a FlowLayout, and your label is then centered in it with a size the minimal one required to let text appear. Then the label is left aligned in its own area, but this one is centered in the panel.

Either change the layout of the panel to let the label extends in it (add a BorderLayout and set the label in north, center or south of it), or remove the panel that seems not useful (and let the label extends in the south of the contentpane.

statusPanel.setLayout(new BorderLayout());


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download