我已经使用 intellij IDE GUI 表单生成了简单的 UI。生成的 java 文件:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class App {
private JButton buttonMessage;
private JPanel panelMain;
public App() {
buttonMessage.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "hello world");
}
});
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setContentPane(new App().panelMain);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
还有我的
build.gradle.kts
:
/*
* This file was generated by the Gradle 'init' task.
*
* This generated file contains a sample Java application project to get you started.
* For more details on building Java & JVM projects, please refer to https://docs.gradle.org/8.3/userguide/building_java_projects.html in the Gradle documentation.
*/
plugins {
// Apply the application plugin to add support for building a CLI application in Java.
application
}
repositories {
// Use Maven Central for resolving dependencies.
mavenCentral()
}
dependencies {
// Use JUnit Jupiter for testing.
testImplementation("org.junit.jupiter:junit-jupiter:5.9.3")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
// This dependency is used by the application.
implementation("com.google.guava:guava:32.1.1-jre")
// ADDED DEPENDENCY HERE
implementation("com.intellij:forms_rt:7.0.3")
}
// Apply a specific Java toolchain to ease working on different environments.
java {
toolchain {
languageVersion.set(JavaLanguageVersion.of(8))
}
}
application {
// Define the main class for the application.
mainClass.set("com.example.j3.App")
}
tasks.named<Test>("test") {
// Use JUnit Platform for unit tests.
useJUnitPlatform()
}
现在即使添加了依赖项
implementation("com.intellij:forms_rt:7.0.3")
按照此处的建议https://intellij-support.jetbrains.com/hc/en-us/community/posts/206152369-idea-IC-gradle-and-swing-forms,在构建并运行 jar 后,我得到
Exception in thread "main" java.lang.NullPointerException
at com.example.j3.App.<init>(App.java:12)
at com.example.j3.App.main(App.java:22)
这是有道理的,因为我在构造函数中没有看到
panelMain
的初始化,而是在new App().panelMain
中未初始化(因此为空)使用。但如果我尝试将构造函数中的 panelMain
初始化为 panelMain = new JPanel();
,那么 IDE 会抱怨:
Assignment to UI-bound field will overwrite field generated by UI Designer
因此,一方面,UI 设计器将尝试在构建时初始化 UI 生成的字段(
buttonMessage
和 panelMain
),但另一方面,它不会向 gradle 通知这样做。因此,如果我 gradle clean build
然后 java -cp app/build/libs/app.jar com.example.j3.App
,那么我会得到空指针异常,因为 gradle build
不考虑 intellij 设计器初始化。那么有没有办法解决这个问题呢?
我也遇到了同样的问题。使用这个插件。有用 https://github.com/File5/intellij-idea-guidesigner-plugin