Java - 与GridBagLayout的两个代码比较 - IllegalArgumentException

时间:2014-04-06 18:48:40

标签: java swing layout gridbaglayout illegalargumentexception

我刚刚为GridBagLayout测试了这段代码,我想知道为什么这段代码出现了错误,但它不是另一段代码。此代码异常IllegalArgumentException: cannot add to layout: constraint must be a string (or null)

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class Layout extends JFrame
{
    gridbag g=new gridbag();

    public Layout()
    {
        add(g, BorderLayout.CENTER);
    }

    public static void main(String[]args)
    {
        Layout lay=new Layout();
        lay.setSize(500, 500);
        lay.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        lay.setLocationRelativeTo(null);
        lay.setVisible(true);
    }

    class gridbag extends JPanel
    {
        private JLabel label=new JLabel("Test");

        public gridbag()
        {
            setLayout(new GridBagLayout());

            GridBagConstraints gbc=new GridBagConstraints();            
            Container container=getContentPane();           
            addC(label, container, gbc, 0, 0, 1, 4, 0, 0);          
        }

        private void addC(Component c, Container container, GridBagConstraints gbc, int C, int R, int nC, int nR, double wX, double wY )
        {
            gbc.gridx=C;
            gbc.gridy=R;
            gbc.gridwidth=nC;
            gbc.gridheight=nR;
            gbc.weightx=wX;
            gbc.weighty=wY;

            container.add(c, gbc);
        }
    }
}

但这段代码有效:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

class gridbag extends JPanel
{
    private JLabel label=new JLabel("Test");

    public gridbag()
    {
        setLayout(new GridBagLayout());

        GridBagConstraints gbc=new GridBagConstraints();            
        Container container=this;
        addC(label, container, gbc, 0, 0, 1, 4, 0, 0);          
    }

    private void addC(Component c, Container container, GridBagConstraints gbc, int C, int R, int nC, int nR, double wX, double wY )
    {
        gbc.gridx=C;
        gbc.gridy=R;
        gbc.gridwidth=nC;
        gbc.gridheight=nR;
        gbc.weightx=wX;
        gbc.weighty=wY;

        container.add(c, gbc);
    }

    public static void main(String[]args)
    {
        gridbag g=new gridbag();
        JFrame frm=new JFrame();
        frm.setSize(500, 500);
        frm.add(g, BorderLayout.CENTER);
        frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frm.setLocationRelativeTo(null);
        frm.setVisible(true);
    }
}

其中一个不同之处是Layout的新JFrame课程,第二个代码直接使用JFrame

1 个答案:

答案 0 :(得分:1)

问题出在这里,这是两个版本之间的另一个区别。

Container container=getContentPane();

尝试

Container container=this;