[英]Get error in Swing java - IllegalArgumentException
试图将一些秋千组件放在架子上。 这段代码可以工作到几天前。 现在它不起作用了,什么也没做。 也许有人可以告诉我这是怎么回事?
public static void main(String[] args) {
JFrame mainFrame = new JFrame();
mainFrame.setSize(500, 400); //Size of frame
mainFrame.setTitle("Cinema City"); //Set title
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel mainLabel = new JLabel("Welcome to Cinema City catalog!");
JLabel actorLabel = new JLabel("Actors: ");
JLabel laLabel = new JLabel("Last added: ");
JLabel searchLabel = new JLabel("How to search ?");
GridBagConstraints gbc = new GridBagConstraints();
mainFrame.add(mainLabel, new GridBagConstraints(4, 0, 1, 3, 1, 1,
GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL,
new Insets(20, 160, 0, 0), 0, 0));
mainFrame.add(actorLabel, new GridBagConstraints(0, 0, 1, 1, 1, 1,
GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL,
new Insets(100, 0, 0, 0), 0, 0));
mainFrame.setVisible(true);
这是错误:
Exception in thread "main" java.lang.IllegalArgumentException: cannot add to layout: constraint must be a string (or null)
at java.awt.BorderLayout.addLayoutComponent(Unknown Source)
at javax.swing.JRootPane$1.addLayoutComponent(Unknown Source)
at java.awt.Container.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at javax.swing.JFrame.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at GUI.main(GUI.java:40)
您实际上并没有将布局设置为GridBagLayout
,因此它仍然是默认设置(它将是FlowLayout
)。
当然,只有GridBagLayout
可以实际处理GridBagConstraints
。 可以通过将声明更改为JFrame mainFrame = new JFrame(new GridBagLayout());
未提及特定JFrame的布局- mainframe
在JFrame声明之后添加此行
mainFrame.setLayout(new GridBagLayout());
应该工作正常。
您没有设置框架布局。 创建框架对象后,编写此代码。
new GridBagLayout();
mainFrame.setLayout(gbl);
是工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.