Java - GridBagLayout/Insets 将 JLabel 置于另一个下

Java - GridBagLayout/Insets position JLabel under another

我用一个 GridBagLayout 和两个 JLabels。我希望第一个出现在左上角,下一个出现在它的右下方和右侧。我使用:

    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);

并且如第一张图片所示显示正常。然后我尝试创建并添加第二个,但我在第一个下方和右侧定位时遇到了一些麻烦。也许我对 Insets 做错了,因为它从顶部给出了额外的 space:

    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);

我该如何解决这个问题?谢谢

尝试这样的事情:

    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);

使用 gridy 和 gridx 属性指定 JLabel 在 GridBagLayout 中的位置-Table。