Search code examples
javaswingjframejpanelborder-layout

Using BorderLayout for adding 4 in-line Components to a JPanel


In my application, there are 4 panels. And i need to insert them into the main panel, which uses BorderLayout. The 4 panels are...

  1. A thin Image strip.
  2. 4 buttons just below above
  3. A TextField covering the complete page.
  4. An about at end.

This is my code...

    add(imageLabel, BorderLayout.NORTH);
    add(buttonPanel,BorderLayout.PAGE_START);
    add(logScrollPane, BorderLayout.CENTER);
    add(about, BorderLayout.PAGE_END);

When I do this, the buttonPanel disappears. How can I achieve what I need?


Solution

  • I usually try to keep a maximum of 3 components in any BorderLayout, so I would do it like this...

    JPanel outerPanel = new JPanel(new BorderLayout());
    JPanel innerPanel= new JPanel(new BorderLayout());
    
    innerPanel.add(buttonPanel,BorderLayout.NORTH);
    innerPanel.add(logScrollPane, BorderLayout.CENTER);
    innerPanel.add(about, BorderLayout.SOUTH);
    
    outerPanel.add(imageLabel, BorderLayout.NORTH);
    outerPanel.add(innerPanel,BorderLayout.CENTER);
    

    As long as you keep the 'maximum-stretched' component in the CENTER (in this case, your logScrollPane) then it'll always work. If you want to use the panel, such as setting it on a JFrame, just use add(outerPanel).

    Don't be afraid of BorderLayout - the ability of this layout to auto-expand the CENTER component to fill the available space make it a very powerful and very important LayoutManager!