gpt4 book ai didi

java - Swing java 中出现错误 - IllegalArgumentException

转载 作者:行者123 更新时间:2023-12-01 22:17:23 25 4
gpt4 key购买 nike

尝试在框架上放置一些 Swing 组件。这段代码几天前还有效。现在不行了,什么也没有了。也许有人可以告诉我出了什么问题?

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

来解决此问题

关于java - Swing java 中出现错误 - IllegalArgumentException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30725929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com