尝试将一些摆动组件放在框架上。 这段代码几天前就开始了。现在它不起作用,什么都没有。 也许有人可以告诉我它错了什么?
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)
答案 0 :(得分:3)
您实际上并未将布局设置为GridBagLayout
,因此它仍然是默认布局(可能是FlowLayout
)。
当然,只有GridBagLayout
才能真正处理GridBagConstraints
。
这可以通过将您的声明更改为JFrame mainFrame = new JFrame(new GridBagLayout());
答案 1 :(得分:0)
特定JFrame未提及布局 - mainframe
在JFrame声明
之后添加此行mainFrame.setLayout(new GridBagLayout());
应该可以正常工作。
答案 2 :(得分:0)
您没有设置框架布局。 创建框架对象后写入此代码。
new GridBagLayout();
mainFrame.setLayout(gbl);
它的工作