【问题标题】:GridBagLayout in Java wont workJava中的GridBagLayout不起作用
【发布时间】:2017-06-05 22:49:50
【问题描述】:

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

I want to sort panels like this

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

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;

    }

}

but it looks like this

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

【问题讨论】:

    标签: java jpanel gridbaglayout gridx


    【解决方案1】:

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

    但是,如果您想/需要使用GridBagLayout,您当前遇到的问题是您将每个面板的 x 和 y 的 weight 设置为 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;
    
    }
    

    【讨论】:

    • 非常感谢你的回答,Java Devil,你帮了我很多。第一张图我其实是用BorderLayout做的,不过最近开始学Java,不知道怎么做resize handler。而且我还在某处读到 GridBagLayout 是最灵活的,所以我想尝试一下。
    猜你喜欢
    • 2014-11-23
    • 1970-01-01
    • 2013-08-22
    • 1970-01-01
    • 2023-03-21
    • 2020-10-27
    • 1970-01-01
    • 2017-11-28
    • 2014-05-23
    相关资源
    最近更新 更多