- 发送方Applet代码:SendApplet.java
package twoAppletComm;
mport java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class SendApplet extends Applet {
TextField tfSend = new TextField("你好,能收到信息了吗 ",20); // 定义文本框
Button btnSend = new Button("发送到Receiver"); // 定义发送按钮
public void init() {
setLayout(new FlowLayout());
add(tfSend);
add(btnSend);
}
public boolean action(Event ev, Object obj){ // 处理按钮事件
if(ev.target instanceof Button){
String msgSend = tfSend.getText();
ReceiveApplet receiveApplet = (ReceiveApplet)getAppletContext().getApplet("ReceiveApplet");
if(receiveApplet != null){
receiveApplet.AppendText(msgSend); // 调用ReceiveApplet中的方法
return true;
}
else{
tfSend.setText("没有找到ReceiveApplet");
return false;
}
}
return false;
}
}
- 接受方代码:ReceiveApplet
package twoappletscom;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class ReceiveApplet extends Applet {
TextField tfReceive = new TextField("准备接收",20);
public void init() {
setLayout(new FlowLayout());
add(tfReceive);
}
public void AppendText(String msg){ // 声明公共方法以便SendApplet调用
tfReceive.setText("收到信息!信息的内容是\""+msg+"\"");
}
}
- Html文件:twoAppletComm.html
<HTML>
<HEAD>
<TITLE>
Web页内两个Applet通信
</TITLE>
</HEAD>
<BODY>
测试Web页内两个Applet通信<BR>
<APPLET CODE = " SendApplet.class"
NAME = "SendApplet"
WIDTH = 300
HEIGHT = 100
HSPACE = 0
VSPACE = 0
ALIGN = left
>
</APPLET>
<APPLET CODE = " ReceiveApplet.class"
NAME = "ReceiveApplet"
WIDTH = 300
HEIGHT = 100
HSPACE = 0
VSPACE = 0
ALIGN = right
>
</APPLET>
</BODY>
</HTML>
|