I have made a Loader Applet which greets the user and when user clicks the button displayed on that Applet it then launches the main applet and the Loader Applet is destroyed.
But on clicking Another applet is not launched !
Loader Applet:
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
public class Loader extends JApplet implements ActionListener{
Display secondApplet;
Button button;
@Override
public void init() {
setSize(800,600);
}
@Override
public void start() {
setLayout(new FlowLayout());
button = new Button ("Click me !!");
add(button);
button.addActionListener(this);
}
@Override
public void paint(Graphics g) {
}
@Override
public void actionPerformed(ActionEvent e) {
secondApplet = (Display)getAppletContext().getApplet("Display");
if (secondApplet != null) {
secondApplet.init();
secondApplet.start();
}
else {
System.out.println("Not Running\n");
}
}
}
Display Applet:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JApplet;
public class Display extends JApplet {
@Override
public void init() {
setSize(600,400);
}
@Override
public void paint(Graphics g) {
g.fillRect(0, 0, this.getWidth(), this.getHeight());
}
}
How can I create an instance of the other Applet and destroy the current Applet !!
Since an Applet/JApple is a java.awt.Panel itself, then you can embed one into the other, for your specific case you can embed Display into Loader using a Panel in Loader to reload Display as you need.
Something like this:
Panel container = new Panel();
container.setLayout(new GridLayout(1,0));
container.add(secondApplet); //Display Applet
add(container):
secondApplet.init();
secondApplet.start();
button.setVisible(false);