javaswinglayout-managerboxlayout

Java BoxLayout place some Objects left and some right


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


Solution

  • 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