문제

I just tested this code for GridBagLayout, I wonder why there's error with this code but it isn't with another code. This code got exception 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);
        }
    }
}

But this code worked:

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

One of the difference is there's a new Layout class for JFrame and the second code use JFrame directly.

도움이 되었습니까?

해결책

The problem is here and this is one more difference between your two versions.

Container container=getContentPane();

Try

Container container=this;      
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top