添加到BorderLayout时无法在JPanel中左对齐JLabel

问题描述 投票:0回答:1

这似乎很简单,但是我无法使其正常工作。

我有一个BorderLayout。我想将顶部用作标题栏。我想添加带有标签,按钮和其他组件的JPanel。但是,BorderLayout的PAGE_START部分不会使我的JPanel对齐。在这种情况下,我尝试设置对齐方式的地方带有注释。

[我注意到,当我不向边框布局中添加JPanel时,直接将JLabel写入其中,默认情况下它已向左对齐。

不过,这不是我想要的,因为我正计划通过BorderLayout.PAGE_START标题区域水平放置BoxLayout.X_AXIS。似乎是一件合理的事情?

静态方法的Container窗格参数只是主JFrame上的单个JPanel。

public static void addComponentsToPane(Container pane) 
    {
        JLabel jlabel = new JLabel("I want to left align this inside a JPanel");
        // Doesn't work: jlabel.setAlignmentX(Component.LEFT_ALIGNMENT);
        JPanel jpanel = new JPanel();
        //Doesn't work: jlabel.setAlignmentX(Component.LEFT_ALIGNMENT);
        jpanel.add(jlabel);
        pane.add(jpanel, BorderLayout.PAGE_START);

        // Other parts of the BoxLayout (works fine)
        JButton button = new JButton("Button 2 (CENTER)");
        button.setPreferredSize(new Dimension(200, 100));
        pane.add(button, BorderLayout.CENTER);

        button = new JButton("Button 3 (LINE_START)");
        pane.add(button, BorderLayout.LINE_START);

        button = new JButton("Long-Named Button 4 (PAGE_END)");
        pane.add(button, BorderLayout.PAGE_END);

        button = new JButton("5 (LINE_END)");
        pane.add(button, BorderLayout.LINE_END);
    }

即使我告诉面板将标签左对齐,它也不会看起来左对齐。

有人知道我在做什么错吗?

问候,

  • 蓝色
java swing alignment layout-manager boxlayout
1个回答
0
投票

默认情况下,JPanel使用具有“中心”对齐方式的FlowLayout

如果要使组件“向左”对齐,则需要在面板上设置布局以使用具有“向左”对齐的FlowLayout

读取FlowLayout API,以获取用于设置对齐方式的适当构造函数。

或者您也可以阅读How to Use FlowLayut上的Swing教程,其中提供了构造函数和用于指定对齐方式的有效值。

© www.soinside.com 2019 - 2024. All rights reserved.