简体   繁体   中英

Can't left align a JLabel within a JPanel when adding to a BorderLayout

This seems like a simple thing to do, but I can't get it to work.

I have a BorderLayout . I want to use the top part for a title bar. I want to add a JPanel with labels, buttons and other components. However, the PAGE_START part of the border layout won't left align the panel. Here's the situation, with comments in where I've tried to set the alignment.

I noticed that when I don't add a panel to the border layout, and just write the JLabel straight in, it has left alignment by default.

This is not what I want, though, because I am planning on putting a BoxLayout.X_AXIS horizontally through the BorderLayout.PAGE_START title area. Seems to be a reasonable thing to do?

The Container pane argument to the static method is just the single panel on the main JFrame .

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);
    }

Even when I tell the panel to left align the label, it doesn't appear left aligned.

Does anyone know what I am doing wrong?

By default a JPanel uses a FlowLayout with "center" alignment.

if you want components "left" aligned, then you need to set the layout on the panel to use a FlowLayout with "left" alignment.

Read the FlowLayout API for the proper constructor to use to set the alignment.

Or you can also read the Swing tutorial on How to Use FlowLayut which gives the constructors and valid values to specify the alignment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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