我有一个小程序,我想导出为独立的可运行 jar 文件。在 IntelliJ IDEA 中如何实现这一点?
我尝试从终端和桌面启动它,它似乎可以打开,但几乎立即退出。使用 IDE 中的运行,该小程序可以正常工作。
最佳答案
Applet 是 javax.swing.Component 的子类,因此您可以像任何其他组件一样将其添加到 JFrame。
因此,您需要做的就是创建一个 main() 方法,该方法创建一个 JFrame 并向其中添加小程序。 这是一个例子:
import javax.swing.*;
import java.awt.*;
public class HelloWorldApplet extends JApplet {
public static void main(String[] args) {
// create and set up the applet
HelloWorldApplet applet = new HelloWorldApplet();
applet.setPreferredSize(new Dimension(500, 500));
applet.init();
// create a frame to host the applet, which is just another type of Swing Component
JFrame mainFrame = new JFrame();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// add the applet to the frame and show it
mainFrame.getContentPane().add(applet);
mainFrame.pack();
mainFrame.setVisible(true);
// start the applet
applet.start();
}
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
JLabel label = new JLabel("Hello World");
label.setHorizontalAlignment(SwingConstants.CENTER);
add(label);
}
});
} catch (Exception e) {
System.err.println("createGUI didn't complete successfully");
}
}
}
关于java - 导出可运行的小程序 IntelliJ IDEA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22925081/