Tuesday 7 April 2020

Inter Applet Communication

What is Inter Applet Communication ?

Inter Applet Communication means the communication of applets to each other in the same browser running simultaneously.
Lets understand it by an example:
suppose if there are 2 applets running in the browser that are applet1 and applet2.
Now suppose we want that when we click on the applet1's button then a message should be displayed on applet2
by using Inter Applet Communication we can do that thing and all those things that are related with the applet's communication.

Now the question is how can we do that?

so java.applet.AppletContext class provides the facility of communication between applets.
we provide the name of applets in the html file and by using this particular name with getApplet() method we can access the particular applet.

Syntax of getApplet() method:

public Applet getApplet(String appletName);

Program

first I am creating the html file named iac.html
<html>
<head>
<title>inter applet communication</title>
</head>
<body>
<applet code="Applet1.class" width="1000" height="500" name="applet1">
</applet>
<hr/>
<applet code="Applet2.class" width="1000" height="500" name="applet2">
</applet>
</body>
</html>

Applet1.java

import java.applet.Applet;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Button;
import java.awt.TextField;
import java.applet.AppletContext;
import java.awt.Label;
public class Applet1 extends Applet implements ActionListener
{
Button b;
TextField tf1;
Label msg1;
public void init()
{
b=new Button("Send to applet2");
tf1=new TextField();
msg1=new Label();
add(b);
add(tf1);
add(msg1);
setLayout(null);
tf1.setBounds(0,20,450,40);
b.setBounds(0,70,100,30);
msg1.setBounds(0,150,450,30);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
AppletContext ctx=getAppletContext();
Applet2 app2=(Applet2)ctx.getApplet("applet2");
app2.msg2.setText(tf1.getText());
}
}

applet2.java

import java.applet.Applet;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Button;
import java.awt.TextField;
import java.applet.AppletContext;
import java.awt.Label;
public class Applet2 extends Applet implements ActionListener
{
Button b;
TextField tf2;
Label msg2;
public void init()
{
b=new Button("Send to Applet1");
tf2=new TextField();
msg2=new Label();
add(b);
add(tf2);
add(msg2);
setLayout(null);
tf2.setBounds(0,20,450,40);
b.setBounds(0,70,100,30);
msg2.setBounds(0,150,450,30);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
AppletContext ctx=getAppletContext();
Applet1 app1=(Applet1) ctx.getApplet("applet1");
app1.msg1.setText(tf2.getText());
}
}

output screenshots:

No comments:

Post a Comment

What is BAT?