Make JPanel takes full width of JFrame

momodjib :

I have two JPanel to place inside a JFrame, I want them both to occupy the full width of the frame but I don't know how. Also I'm not a big fan of the setBounds() method so I was wondering if there is a way to just make the component take the full width and just specify the desired height after.

Here is my code:

public class Test extends JFrame {
    public Test() {

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 400);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout());

        JPanel header = new JPanel();
        header.setBounds(0,0,300,50);
        header.setLayout(new BorderLayout());
        header.setBackground(Color.gray);

        JPanel body = new JPanel();
        body.setBounds(0,50,300,300);
        body.setLayout(new BorderLayout());
        body.setBackground(Color.black);


        add(header, BorderLayout.NORTH);
        add(body, BorderLayout.CENTER);
        //setLayout(null);
        setVisible(true);


    }
}
Adam :

You need to remove the setLayout(null), this reverses the work of the earlier setLayout(new BorderLayout())

You then need to set the preferred size of both the header and body using setPreferredSize instead of using setBounds()

public Test() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(400, 400);
    setLocationRelativeTo(null);
    setLayout(new BorderLayout());

    JPanel header = new JPanel();
    header.setPreferredSize(new Dimension(400, 50));
    header.setLayout(new BorderLayout());
    header.setBackground(Color.gray);

    JPanel body = new JPanel();
    body.setPreferredSize(new Dimension(400, 300));
    body.setLayout(new BorderLayout());
    body.setBackground(Color.black);

    add(header, BorderLayout.NORTH);
    add(body, BorderLayout.CENTER);
    setVisible(true);
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=415370&siteId=1