因此,我尝试使用Java在Intellij中编译一个简单的GUI,但是在运行代码时,我始终收到错误消息。我昨天没有收到此错误,此后没有任何变化。该项目具有gradle依赖性-当前为空。
要解决此问题,我已经卸载并重新安装了Java 8和Intellij 2019.1.1-无济于事。
主要
public class application {
public static void main(String[] args) {
AppGUI appGUI = new AppGUI();
appGUI.setVisible(true);
}
}
gui
import javax.swing.*;
public class AppGUI extends JFrame{
private JPanel rootLabel;
private JLabel testLabel;
public AppGUI() {
add(rootLabel);
setSize(400,500);
}
}
渐变
plugins {
id 'java'
}
group 'liamgooch'
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
}
我收到以下错误消息:
6:17:13 PM: Executing task 'application.main()'...
> Task :compileJava UP-TO-DATE
> Task :processResources NO-SOURCE
> Task :classes UP-TO-DATE
> Task :application.main() FAILED
Exception in thread "main" java.lang.NullPointerException
at java.awt.Container.addImpl(Container.java:1095)
at java.awt.Container.add(Container.java:1007)
at javax.swing.JFrame.addImpl(JFrame.java:567)
at java.awt.Container.add(Container.java:419)
at AppGUI.<init>(AppGUI.java:8)
at application.main(application.java:3)
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':application.main()'.
> Process 'command 'C:/Program Files/Java/jdk1.8.0_212/bin/java.exe'' finished with non-zero exit value 1
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 1s
2 actionable tasks: 1 executed, 1 up-to-date
Process 'command 'C:/Program Files/Java/jdk1.8.0_212/bin/java.exe'' finished with non-zero exit value 1
6:17:15 PM: Task execution finished 'application.main()'.
答案 0 :(得分:3)
原因是因为您没有在AppGUI类中初始化了JLabel
和JPanel
。
rootLabel = new JPanel();
testLabel = new JLabel();
答案 1 :(得分:2)
您说它正在工作?我不知道如何。在您发布的代码中,我看不到在何处为变量rootLabel
分配值。因此,它为null,因此在使用空参数调用类NullPointerException
的方法add
时会得到一个JFrame
。它说,所以在您发布的堆栈跟踪中...
at AppGUI.<init>(AppGUI.java:8)