早上好,
我在使用 Java - Swing 时遇到了一个奇怪的问题。 这是我的主要方法
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
PrincipalWindow windowImportLoadCurve = new PrincipalWindow();
JFrame.setDefaultLookAndFeelDecorated(true);
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
setModelViewTable(windowImportLoadCurve);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
从 Eclipse IDE (Neon 2.0) 内部运行它。它创建了 4 个线程
Daemon Thread [AWT-Windows] (Running)
Thread [DestroyJavaVM] (Running) -> Main
Thread [AWT-Shutdown] (Running)
Thread [AWT-EventQueue-0] (Running)
它正常运行并工作,JVM 在 GUI 应用程序完成时关闭。所以我使用 Maven Install 和外部依赖项生成了一个 jar
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>weblogic-client-unpack</id>
<phase>generate-resources</phase>
<goals>
<goal>unpack</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<outputDirectory>${project.build.directory}/</outputDirectory>
</artifactItem>
</artifactItems>
</configuration>
</execution>
<execution>
<id>jboss-client-unpack</id>
<phase>generate-resources</phase>
<goals>
<goal>unpack</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<outputDirectory>${project.build.directory}/</outputDirectory>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<id>ingrid-load-generator-package-assembly</id>
<phase>install</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<manifest>
<mainClass>main.MainGenerator</mainClass>
</manifest>
<descriptors>
<descriptor>src/main/assembly/assembly-bin.xml</descriptor>
</descriptors>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
然后开始使用 bat 运行。同一应用程序创建相同的 4 个线程,因此它打开 GUI(使用 SwingUtility.invokeLater() 线程)并继续运行主程序。但当 GUI 实际打开时,它会立即关闭,无需任何用户操作。
最佳答案
我的第一个猜测是错误的。
尝试仅使用 swing 组件创建/发布一个最小的代码示例,以显示您所看到的行为。
这是一个适合我的示例:
public class Test {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame jf=new JFrame("Hi");
jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JF.setSize(500,200);
jf.setVisible(true);
}});}}
如果这对您不起作用,则可能与您的环境有关。如果它确实适合您,请使用它作为起点并开始将其转换为更像您的代码,并在每次更改后运行测试。当您找到破坏它的更改时,您就有了答案。
关于java - 为什么我的 Swing 主线程死掉了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45616249/