Make Your Program Both an Applet and an Application

Sometimes it’s convenient to have your program be runnable both as an applet and as an application. One simple way of accomplishing this derives from the fact that any class can have a main method. If you’ve written your program as an applet, just add a main method, in which you instantiate the applet class and display it in a frame. For example:

public class MyApplet extends JApplet {  ...  public static void main(String[] args) {    Component applet = new MyApplet();    JFrame frame = new JFrame("My applet, as application");    frame.getContentPane().add(applet);    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    frame.pack();    frame.show();}

Of course, depending on what components your applet displays, you may want to set the size explicitly rather than packing.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: