user1477384
user1477384

Reputation: 11

Adding a main class to an applet

I added a main method to a Java applet in order to run it as an application but it requires me to initialize all the methods in the class that contains the main. I managed to initialize the init method but I have failed to initialize all methods that carry on arguments.

Any one with an idea on how to proceed?

Upvotes: 1

Views: 5652

Answers (2)

Andrew Thompson
Andrew Thompson

Reputation: 168845

There is more to starting some applets than simply calling the start() and init() methods. Many applets require a valid AppletContext and AppletStub in order to work correctly.

The best strategy would be to factor the GUI into a separate class that is added either to an applet or frame as needed. This is called an 'hybrid application/applet'. Subway is a good example of an hybrid, though it does not accept arguments. For the arguments, accept them in the constructor of the GUI class, or include get/set methods for them. The applet would use getParam(String) to determine what values to use, while the application would get the arguments from the String[] from main(String[] args).

Upvotes: 3

Reimeus
Reimeus

Reputation: 159874

Here is code from a working application. Note how the applet methods are called:

    JFrame frame = new JFrame();
    frame.setSize(400, 300);

    final Applet applet = new MyCustomApplet();

    frame.getContentPane().add(applet);
    frame.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent we) {
            applet.stop();
            applet.destroy();
            System.exit(0);
        }
    });

    frame.setVisible(true);
    applet.init();
    applet.start();

Upvotes: 6

Related Questions