导出可运行的小程序IntelliJ IDEA

时间:2014-04-07 23:44:29

标签: java intellij-idea applet

我有一个applet我想导出为独立的可运行jar文件。如何在IntelliJ IDEA中实现这一目标?

我尝试从终端和桌面启动它,它似乎打开但几乎立即退出。使用IDE中的run,applet工作正常。

1 个答案:

答案 0 :(得分:1)

Applet是javax.swing.Component的子类,因此您可以像任何其他组件一样将其添加到JFrame。

因此,您需要做的就是创建一个main()方法,创建一个JFrame并将applet添加到它。 这是一个例子:

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");
      }
    }
}
相关问题