Search code examples
javaswinglayoutswtborder-layout

borderlayout in swt or swing


I want to arrange components as shown in image. I can do this by using gridbaglayout but I want to do this using borderlayout. I tried it but could not achieve what I wanted. so please guide me here. The black rectangles here are components like JPanel, Button etc.

enter image description here


Solution

  • If you want to do it only with BorderLayout, you need to use 2 BorderLayout. If you cannot use 2 layouts, then you are stuck with GridBagLayout. This is a demonstration of what I am telling:

    import java.awt.BorderLayout;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    
    public class Test {
    
        protected void initUI() {
            JFrame frame = new JFrame("test");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel panel = new JPanel(new BorderLayout());
            JPanel panel2 = new JPanel(new BorderLayout());
            panel2.add(new JButton("NORTH"), BorderLayout.NORTH);
            panel2.add(new JButton("CENTER"));
            panel.add(panel2);
            panel.add(new JButton("SOUTH"), BorderLayout.SOUTH);
            panel.add(new JButton("EAST"), BorderLayout.EAST);
            frame.add(panel);
            frame.pack();
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
    
                @Override
                public void run() {
                    new Test().initUI();
                }
            });
        }
    }
    

    Example