In certain scenarios, you may need an existing Applet to launch another Applet to perform other task.

Here’s two files for demonstration

1. AppletExample1.java
2. AppletExample2.java

The “AppletExample1.java” contains a “Thread” and launch “AppletExample2.java” after 5 seconds.

1. AppletExample1.java

package com.mkyong.applet;
 
import java.applet.Applet;
import java.applet.AppletStub;
import java.awt.Graphics;
import java.awt.GridLayout;
 
public class AppletExample1 extends Applet
implements Runnable, AppletStub {
 
	Thread threadABC;
 
	public void init(){}
 
	public void paint(Graphics g) {
	    g.drawString("I'm Applet 1 ~", 10, 10);
	    g.drawString("Loading Applet 2 ...", 10, 30);
 
	} 
 
	public void run() {
 
	  try {
 
	    //sleep for 5 seconds , for demo
	    threadABC.sleep(5000);
 
	    Class applet2 = Class.forName("com.mkyong.applet.AppletExample2");
	    Applet appletToLoad = (Applet)applet2.newInstance();
	    appletToLoad.setStub(this);
	    setLayout( new GridLayout(1,0));
	    add(appletToLoad);
	    appletToLoad.init();
	    appletToLoad.start();
 
	  }catch (Exception e) {
	    System.out.println(e);
	  }
 
	    validate();
	}
 
	public void start(){
	    threadABC = new Thread(this);
	    threadABC.start();
	}
 
	public void stop() {
	    threadABC.stop();
	    threadABC = null;
	}
 
	public void appletResize( int width, int height ){
	    resize( width, height );
	}
 
}

2. AppletExample2.java

package com.mkyong.applet;
 
import java.applet.Applet;
import java.awt.Graphics;
 
public class AppletExample2 extends Applet{
 
	public void init(){	}
 
	public void paint(Graphics g) {
	    g.drawString("I'm Applet 2 ~", 10, 10);
	} 
 
}

3. HTML load Applet

There are no different to load “AppletExample1″, just load it as normal :

<html>
<head><title>Testing</title></head>
<body>
<applet width=300 height=300 code="com.mkyong.applet.AppletExample1.class"> 
</applet>
</body>
</html>

4. Done

You will notice Applet will display (AppletExample1)

"I'm Applet 1 ~"
"Loading Applet 2 ..."

After 5 seconds, it will change to (AppletExample2)

I'm Applet 2 ~"

How about the Applet parameter?

Both Applets will sharing the same parameters specified within applet tag.

For example,

<applet width=300 height=300 code="com.mkyong.applet.AppletExample1.class"> 
<param name="paramUrl" value="http://www.mkyong.com">
</applet>

Both “AppletExample1.java” and “AppletExample2.java” are able to access the “paramUrl” value with getParameter(“paramUrl”) method.

Any Java questions or problems? please post at this JavaNullPointer.com forum, see you there ~