-1

i want to place child components to a JPanel. But the problem is, that i want to place the components on the left-hand side and on the right-hand side of the parent JPanel. I'am using a BoxLayout and currently i have set the X Alignment of the child components. My problem is showed here: MyProblem

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Chippi_5
  • 1
  • 4

1 Answers1

1

There are a lot of ways to achieve what you are looking for.

When using BoxLayout, I usually place the components into nested panels.

See my example where I use BoxLayout with X_AXIS for each component. You could use another LayoutManagers as well, this is just an example:

public class BoxLayoutAlign {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            UIManager.put("Label.font", new Font("Calibri", Font.PLAIN, 20));
            createGui();
        });
    }

    private static void createGui() {
        JFrame frame = new JFrame("example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel contentPanel = new JPanel();
        contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS));
        frame.setContentPane(contentPanel);

        JLabel left = new JLabel("Left");

        JLabel right = new JLabel("Right");

        JLabel center = new JLabel("Center");

        contentPanel.add(placeLeft(left));
        contentPanel.add(placeRight(right));
        contentPanel.add(placeCenter(center));

        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    static JPanel createBoxXWith(Component... components) {
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
        for (Component c : components)
            panel.add(c);
        return panel;
    }

    static JPanel placeRight(Component component) {
        return createBoxXWith(Box.createHorizontalGlue(), component);
    }

    static JPanel placeLeft(Component component) {
        return createBoxXWith(component, Box.createHorizontalGlue());
    }

    static JPanel placeCenter(Component component) {
        return createBoxXWith(Box.createHorizontalGlue(), component, Box.createHorizontalGlue());
    }
}

It results to:

enter image description here

George Z.
  • 6,643
  • 4
  • 27
  • 47
  • Hi George, this solution works! But now i am interrested in how you would do it with nested panels. Can you explain it to me? – Chippi_5 Sep 29 '21 at 18:49
  • or how you would solve it with other LayoutManagers? – Chippi_5 Sep 29 '21 at 18:55
  • @Chippi_5 See my method. It uses nested BoxLayout panels. And these panels are added to the parent panel. This is nesting. About other layout manager, see the link. I support `BorderLayout` and `FlowLayout` can achieve it too. – George Z. Sep 29 '21 at 19:35
  • ok thank you very much! – Chippi_5 Sep 29 '21 at 19:37