How to an Applet send message to another Applet on the same page
In this tutorial, you will learn how to an Applet communicate / send message / access data from/to another Applet on the same page.
Here’s two Applet files for demonstration.
1. AppletExample1 – Contains a button, will change the AppletExample2′s name after clicked.
2. AppletExample2 – Contains a “TextArea”, display it’s name.
The communication is through the getAppletContext().getApplet(“Applet Name”), which will return the Applet by name.
P.S The Applet name is specified in HTML page, NOT your Applet’s class name.
1. AppletExample1.java
package com.mkyong.applet; import java.applet.Applet; import java.awt.Button; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class AppletExample1 extends Applet implements ActionListener { Button button; public void init(){ button = new Button("Change AppletExample2's name"); button.setActionCommand("CHANGEME"); button.addActionListener(this); add(button); } @Override public void actionPerformed(ActionEvent e) { if(e.getActionCommand().equals("CHANGEME")){ AppletExample2 appExample2 = (AppletExample2)getAppletContext().getApplet("HtmlApplet2"); appExample2.setName("Your name changed by Applet1"); } } }
2. AppletExample2.java
package com.mkyong.applet; import java.applet.Applet; import java.awt.FlowLayout; import java.awt.TextArea; public class AppletExample2 extends Applet{ String name; TextArea textBox; public void init(){ name = "no name"; setLayout(new FlowLayout()); textBox = new TextArea(5,40); add(textBox); } public void setName(String name){ this.name = name; textBox.append(this.name); } }
3. HTML
<html> <head><title>Testing 1234</title></head> <body> <h1>AppletExample1</h1> <applet width=300 height=100 code="com.mkyong.applet.AppletExample1.class"> </applet> <h1>AppletExample2</h1> <applet width=300 height=100 name="HtmlApplet2" code="com.mkyong.applet.AppletExample2.class"> </applet> </body> </html>
The “AppletExample2″ can be retrieve by “HtmlApplet2″ Applet’s name – getAppletContext().getApplet(“HtmlApplet2″);
4. Output
