Search code examples
javaswingawtgridbaglayoutinsets

Java - GridBagLayout/Insets position JLabel under another


I use a GridBagLayout and have two JLabels. I want the first one to appear on the top left and the next one right below it and to the right. I use:

    setLayout(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.insets = new Insets(10, 10, 10, 10);

    JLabel jl = new JLabel("This is a JLabel!", SwingConstants.CENTER);
    jl.setBorder(BorderFactory.createLineBorder(Color.black));
    gbc.ipadx = 87;
    gbc.ipady = 220;
    add(jl, gbc);

And is displayed fine as first pic shows. Then I try to create and add the second one but I have some troubles positioning below and right the first one. Maybe I do something wrong with the Insets as it gives extra space from the top:

    gbc.insets = new Insets(500, 10, 10, 10);
    JLabel jl2 = new JLabel("This is a JLabel!", SwingConstants.CENTER);
    jl2.setBorder(BorderFactory.createLineBorder(Color.black));
    gbc.ipadx = 87;
    gbc.ipady = 220;
    add(jl2, gbc);

How can I fix this? Thanks

enter image description here enter image description here


Solution

  • Try something like this:

        GridBagLayout gbl=new GridBagLayout();
        setLayout(gbl);
        GridBagConstraints gbc=new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);
    
        JLabel jl = new JLabel("This is a JLabel!", SwingConstants.CENTER);
        jl.setBorder(BorderFactory.createLineBorder(Color.black));
        gbc.gridy = 0;
        gbc.gridx = 0;
        gbc.ipadx = 50;
        gbc.ipady = 50;
        add(jl, gbc);
    
        gbc.insets = new Insets(10, 10, 10, 10);
        JLabel jl2 = new JLabel("This is a JLabel!", SwingConstants.CENTER);
        jl2.setBorder(BorderFactory.createLineBorder(Color.black));
        gbc.gridy = 1;
        gbc.gridx = 1;
        gbc.ipadx = 50;
        gbc.ipady = 50;
        add(jl2, gbc);
    

    Use the gridy and gridx attributes to specify the position of the JLabels in the GridBagLayout-Table.