Send a message from an Applet to another Applet on a different pageTag(s): Javascript interaction
FirstApplet encodes the message for SecondApplet in the search (or query) section of SecondApplet.html URL. A simple script in SecondApplet.html decodes the search section and dynamically creates a new page containing the APPLET tag for SecondApplet and a PARAM with the message coming from FirstApplet.
FirstApplet.html
<HTML><HEAD></HEAD><BODY>
<APPLET CODE="FirstApplet.class"
HEIGHT=100
WIDTH=300>
</APPLET></BODY></HTML>import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
public class FirstApplet extends Applet implements
ActionListener {
Button b;
TextField t;
public void init() {
add(new Label("Message to 2nd applet :"));
add(t= new TextField(20));
add(b = new Button("Load 2nd applet"));
b.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == b) {
try {
getAppletContext().showDocument
(new URL(getCodeBase(),
"SecondApplet.html?" + "message="
+ URLEncoder.encode(t.getText())));
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}<HTML><HEAD></HEAD><BODY>
<SCRIPT>
// from Javascript How-to general part 3,
// replace all occurrence of token by another
// in a string.
function replace(s, t, u) {
i = s.indexOf(t);
r = "";
if (i == -1) return s;
r += s.substring(0,i) + u;
if ( i + t.length < s.length)
r += replace(s.substring(i + t.length, s.length), t, u);
return r;
}
strlen = document.location.search.length
if (strlen > 0) {
theMessage = document.location.search
// strip the "message header"
theMessage = theMessage.substring(1 + 'message='.length,strlen)
// replace all '+" by space
theMessage = replace(theMessage, '+', ' ')
// replace encoded chars by decoded chars if any
theMessage = unescape(theMessage)
html = '<APPLET CODE="SecondApplet.class"'
html += ' HEIGHT=100'
html += ' WIDTH=400> '
html += '<PARAM NAME="Message" VALUE="' + theMessage + '"> '
html += '</APPLET>'
document.close()
document.open()
document.write(html)
document.close()
}
</SCRIPT>
</BODY></HTML>import java.applet.*;
import java.awt.*;
public class SecondApplet extends Applet {
public void init() {
Label l = new Label("Message from 1st Applet");
add (l);
TextField tf = new TextField( 50 );
add(tf);
String s = getParameter("Message");
tf.setText(s);
}
}This method is useful when you need to pass the message to the SecondApplet via PARAM tag. But if you don't need the PARAM tag, take a look at this Java How-to.
mail_outline
Send comment, question or suggestion to howto@rgagnon.com
Send comment, question or suggestion to howto@rgagnon.com