0

我使用 aGridBagLayout并有两个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因为它从顶部提供了额外的空间:

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

我怎样才能解决这个问题?谢谢

在此处输入图像描述 在此处输入图像描述

4

1 回答 1

1

尝试这样的事情:

    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 属性来指定 JLabels 在 GridBagLayout-Table 中的位置。

于 2015-09-07T17:44:29.857 回答