-1

我一直在尝试按照我想要的方式调整我的显示器,但它似乎不起作用。我想使用 GridBagLayout 来做这样的事情:

我想像这样对面板进行排序在此处输入图像描述

我找到了一段代码,并对其进行了编辑:

public class GBLPanel extends JPanel 
{
    private static final long serialVersionUID = 1L;

    GridBagConstraints gbc = new GridBagConstraints();

    public GBLPanel(Dimension appdim)
    {
        GridBagConstraints c = new GridBagConstraints();

        setLayout(new GridBagLayout());
        add(gbcComponent(0,0,2,1,0,0), gbc);               
        add(gbcComponent(0,1,1,1,0,50), gbc);            
        add(gbcComponent(1,1,1,1,0,50), gbc); 

    }

     private JPanel gbcComponent(int x, int y, int w, int h, int ipadyx, int ipadyy){

        gbc.gridx = x; 
        gbc.gridy = y;
        gbc.gridwidth = w;
        gbc.gridheight = h;

        gbc.weightx = 1.0;
        gbc.weighty = 1.0;

        gbc.ipadx=ipadyx;
        gbc.ipady=ipadyy;

        gbc.fill = GridBagConstraints.BOTH;
        JPanel panel = new JPanel();
        JTextField text = new JTextField("(" + w + ", " + h + ")");
        panel.setBorder(new TitledBorder("(" + x + ", " + y + ")"));        
        panel.add(text);
        return panel;

    }

}

但它看起来像这样 在此处输入图像描述

我不知道如何按照我的意愿塑造它,任何人都可以帮忙吗?非常感谢 !

4

1 回答 1

2

ABorderLayout可能会更容易为您执行此操作。

但是,如果您想/需要使用 a GridBagLayout,您当前遇到的问题是您将weight每个面板的 x 和 y 都设置为 1。这意味着它们都将均匀分布。

尝试通过执行以下操作更改它们以反映您想要的值

public GBLPanel(Dimension appdim)
{
    GridBagConstraints c = new GridBagConstraints();

    setLayout(new GridBagLayout());
    // Pass in weights also
    add(gbcComponent(0,0,2,1,0,0, 1, 0.25), gbc);  // 100% x and 25% y
    add(gbcComponent(0,1,1,1,0,50, 0.25, 0.75), gbc); // 25% x and 75% y
    add(gbcComponent(1,1,1,1,0,50, 0.75, 0.75), gbc); // 75% x and 75% y

}

private JPanel gbcComponent(int x, int y, int w, int h, int ipadyx, int ipadyy, double wx, double wy)
{
    gbc.gridx = x;
    gbc.gridy = y;
    gbc.gridwidth = w;
    gbc.gridheight = h;

    gbc.weightx = wx;  // Set to passed in values here
    gbc.weighty = wy;

    gbc.ipadx=ipadyx;
    gbc.ipady=ipadyy;

    gbc.fill = GridBagConstraints.BOTH;
    JPanel panel = new JPanel();
    JTextField text = new JTextField("(" + w + ", " + h + ")");
    panel.setBorder(new TitledBorder("(" + x + ", " + y + ")"));
    panel.add(text);
    return panel;

}
于 2017-06-05T23:30:52.870 回答