简体   繁体   English

如何在JPanel内左对齐JLabel?

[英]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) {

        super((Dialog)null);

        this.setTitle(title);

        Initialize();
    }

    protected void Initialize() {

        lblTopSpace = new JLabel("Login into Bookyard");
        lblTopSpace.setForeground(this.getBackground());

        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));
        lblStatus.setHorizontalAlignment(SwingConstants.LEFT);
        statusPanel.add(lblStatus);

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

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

        this.pack();
    }
}

Here is what it looks like presently. 这是目前的样子。

在此处输入图片说明

What am I missing? 我想念什么?

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. 但是,您无需为其设置任何特定的布局,那么它就是FlowLayout ,然后您的标签将在其中居中,其大小应为允许文本显示的最小尺寸。 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. 更改面板的布局以使标签在其中延伸(添加BorderLayout并将标签设置在其北,中或南),或删除似乎无用的面板(并让标签在其南部延伸)内容窗格。

statusPanel.setLayout(new BorderLayout());
statusPanel.add(lblStatus,BorderLayout.SOUTH);

or 要么

container.add(lblStatus,BorderLayout.SOUTH);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM