You are here

Creating a Class that is Both Applet and Application

So far in this article we have only created applets. How does Java know if a class is an applet or an application?

  • If a class has a main method, its an application
  • If a class extends Applet, its an applet

Using these two criteria, Java is able to quickly determine if a class is an applet or an application. You may be thinking that these two conditions are NOT mutually exclusive. What if a class has a main method, and also extends from applet? If this is that case, then that class would be both an applet and an application.

It can be handy to create classes that are both applets and applications. This allows you to run your class both from a browser, and as a normal window. Lising 1l.5 shows the source code used to create an applet that is also an application.

Listing 1.5: An Applet and Application (

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class AppletApplication extends Applet
  public static final int IDEAL_WIDTH = 640;
  public static final int IDEAL_HEIGHT = 480;

  public void paint(Graphics g)

    FontMetrics fm = g.getFontMetrics();
    int y = fm.getHeight();

    g.drawString("Hello World",10,y);

  public static void main(String args[])
    Applet applet = new AppletApplication();
    Frame frame = new Frame();
    frame.addWindowListener(new WindowAdapter()
      public void windowClosing(WindowEvent e)


As you can see this program contains a main method that creates a Frame. The applet is then attached to the frame and displayed.

But how does the program know how big to make the Window? With an applet, the size is specified by the HTML. The applet defines two constants that specify how large the frame should be made.

public static final int IDEAL_WIDTH = 640;
public static final int IDEAL_HEIGHT = 480;

Creating a class that is both an applet and application is convenient, as you can run your program easily in multiple ways.


Theme by Danetsoft and Danang Probo Sayekti inspired by Maksimer