Search code examples
javaswinglayoutgridbaglayoutborder-layout

Problem in setting layout


I have made a JFrame and inside that frame, there is panel on which I have placed various containers using GridBagLayout. I have set layout of JFrame to be BorderLayout, and added panel in BorderLayout.WEST. I want to show that panel's containers at the top left corner. How can I do that?

Even if I try to add panel to BorderLayout.NORTH then also it is displayed in top center but instead I want to be in top left corner.

Is there any way to do that? I.E. any other layout I should use as I want to show

label1
button1     button2     button3

label2
button1     button2     button3

label 3
button1     button2     button3

Solution

  • This is easy to do with just GridLayout and BorderLayout.

    Label-Button Layout

    import java.awt.*;
    import javax.swing.*;
    
    class LabelButtonLayout {
    
        public static Component getButtonLayout(int num) {
            JPanel p = new JPanel(new BorderLayout(3,3));
    
            p.add(new JLabel("Label " + num), BorderLayout.NORTH);
    
            JPanel b = new JPanel(new GridLayout(1,0,25,5));
            for (int ii=1; ii<4; ii++) {
                b.add(new JButton("Button " + ii));
            }
            p.add(b, BorderLayout.CENTER);
    
            return p;
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater( new Runnable() {
                public void run() {
                    JPanel gui = new JPanel(new GridLayout(0,1,3,15));
                    for (int ii=1; ii<4; ii++) {
                        gui.add(getButtonLayout(ii));
                    }
                    JOptionPane.showMessageDialog(null, gui);
                }
            });
        }
    }