Search code examples
javaswinglayout-managerjcomponentboxlayout

How to set position to JComponent in BoxLayout?


I want to use 2 JPanel as panel and panel_1. I want to add image automatically to panel using JLabel and also add JButton to panel_1.

How can I resize button according to the image which is above the button?

public class Testing extends JFrame {

    public Testing() {
        this.setSize(590, 327);
        this.setTitle("JFrame");
        getContentPane().setLayout(null);

        JPanel panel = new JPanel();
        panel.setBounds(118, 136, 321, 89);
        getContentPane().add(panel);
        panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));

        JLabel lblImage = new JLabel("image for button1");
        panel.add(lblImage);

        JLabel lblImage_1 = new JLabel("image for button2");
        panel.add(lblImage_1);

        JLabel lblImage_2 = new JLabel("image for button3");
        panel.add(lblImage_2);

        JPanel panel_1 = new JPanel();
        panel_1.setBounds(118, 30, 321, 77);
        getContentPane().add(panel_1);
        panel_1.setLayout(new BoxLayout(panel_1, BoxLayout.X_AXIS));

        JButton btnNewButton = new JButton("New button 1");
        panel_1.add(btnNewButton);

        JButton btnNewButton_1 = new JButton("New button 2");
        panel_1.add(btnNewButton_1);

        JButton btnNewButton_2 = new JButton("New button 3");
        panel_1.add(btnNewButton_2);
    }

    public static void main(String[] args) throws Exception {
        Testing frame = new Testing();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    }
}

Solution

  • If your goal is to have the button above the image, and have the button's width expand with the image, then:

    • Get rid of your use of null layouts and .setBounds(...) (this is just good general advice)
    • Put the JLabel with the image into a JPanel that uses BorderLayout with the JLabel in the BorderLayout.CENTER position
    • Put the button above the JLabel in the same JPanel using the BorderLayout.PAGE_START position.
    • Then put that JPanel wherever it is needed in the GUI, nesting JPanels, each using their own layout manager.

    The BorderLayout will allow the center component to fill that position, and will expand the PAGE_START and PAGE_END positions to fill the width necessary. If the top and bottom components are wider, then this will also expand the width of the container.