我刚刚为 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
。
问题就在这里,这是两个版本之间的另一个区别。
Container container=getContentPane();
尝试
Container container=this;