javaswinglayout-managerborder-layoutnull-layout-manager

Null Layout not showing over Border Layout in Java


Greeting of the day, I have a JFrame and a Jpanel named panelMain. all my set-up for both the frame and panel are perfect. I have set the Layout of panelMain to BorderLayout. I have now created another panel named panel1. panel1 has a null layout. I added some buttons to panel1 (which has a null layout). then I added panel1 to WEST of panelMain. when I ran the program, panelMain showed up, but panel1 didn't. then I changed the Layout of panel1 from null to FlowLayout, then it appeared on the WEST side of panelMain. I don't know what problem is null layout facing when put in BorderLayout, can someone please help me out.

JPanel panelMain = new JPanel();
JPanel panelWEST = new JPanel();
JButton button = new JButton();
JButton button2 = new JButton();
Constructor(){
    setContentPane(panelMain);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setExtendedState(Frame.MAXIMIZED_BOTH);

    panelMain.setLayout(new BorderLayout());
    panelMain.setBackground(Color.CYAN);

    panelWEST.setLayout(null);
   

    button.setBounds(50,50,200,200);
    button.setText("West Button1");
    button2.setBounds(50,300,200,200);
    button2.setText("West Button2");
    panelWEST.setBackground(Color.PINK);
    panelWEST.add(button);
    panelWEST.add(button2);

    panelMain.add(panelWEST,BorderLayout.WEST);
    

Solution

  • Don't use null layouts!!! Swing was designed to be used with layout managers.

    It is never a good idea to use random numbers and that is exactly what you are doing when you try to guess the size of a component.

    It is the responsibility of each Swing component to determine its own preferred size. The layout manager then uses this information to set the size/location of components added to the panel. When you use a null layout you lose this functionality.

    As a solution you might do something like:

    JPanel buttonPanel = new JPanel( new GridLyaout( 0, 1) );
    buttonPanel.add(button1);
    buttonPanel.add(button2);
    
    JPanel west = new JPanel( new BorderLayout() );
    west.add(buttonPanel, BorderLayout.PAGE_START);
    
    panelMain.add(west, BorderLayout.LINE_START);
    

    If you want space on the left of the buttonPanel, then you can use an EmptyBorder. Read the Swing Tutorial for working examples. There area sections on:

    1. How to Use Borders
    2. A Visual Guide to Layout Managers