Intellij (Swing) GUI 构建器导致 Gradle 问题

问题描述 投票:0回答:1

尝试将简单的 GUI 添加到我的 java 项目后,出现以下错误:

Exception in thread "main" java.awt.IllegalComponentStateException: contentPane cannot be set to null.
    at java.desktop/javax.swing.JRootPane.setContentPane(JRootPane.java:586)
    at java.desktop/javax.swing.JFrame.setContentPane(JFrame.java:680)
    at net.astraleth.studios.gui.TestGUI.<init>(TestGUI.java:21)
    at net.astraleth.studios.Launcher.main(Launcher.java:15)

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':Launcher.main()'.
> Process finished with non-zero exit value 1

这就是我的 GUI 类的结构:

public class TestGUI extends JFrame {


    private JPanel contentPane;
    private JTabbedPane tabbedPane1;

    public TestGUI() {
        this.setIconImage(new ImageIcon(Objects.requireNonNull(getClass().getResource("/assets/icons/icon.png"))).getImage());
        this.setContentPane(contentPane);
        this.setSize(1200, 700);
        this.setLocationRelativeTo(null);
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

这就是我目前的显示方式:

public class Launcher {


    public static void main(String[] args) {
        TestGUI test = new TestGUI();
    }
}

我认为这与 Gradle 有关,因为在切换之前代码运行没有任何问题。如果我只是在 IntelliJ 中打开它,它甚至仍然可以运行,但如果我决定构建一个可运行的 jar,我会收到错误

java swing user-interface intellij-idea
1个回答
0
投票

在你的情况下

contentPane
未初始化。因此,您得到的错误是
contentPane cannot be set to null.

首先初始化'contentPane',然后进行如下设置,

public class TestGUI extends JFrame {

    private JPanel contentPane;
    private JTabbedPane tabbedPane1;

    public TestGUI() {
        contentPane = new JPanel(); // initialize the contentPane
        this.setIconImage(new ImageIcon(Objects.requireNonNull(getClass().getResource("/assets/icons/icon.png"))).getImage());
        this.setContentPane(contentPane);
        this.setSize(1200, 700);
        this.setLocationRelativeTo(null);
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

请参阅 java 文档以获取有关 RootPaneContainer

的更多信息
© www.soinside.com 2019 - 2024. All rights reserved.