在Applet类中提供了许多方法,使之可以与浏览器进行通信。下面对这些方法进行简要的介绍:
一个Web页可包含一个以上的小应用程序。一个Web页中的多个小应用程序可以直接通过java.applet包中提供的方法进行通信。
getDocumentBase( ) //返回当前网页所在的URL
getCodeBase( ) //返回当前applet所在的URL
getImage(URL base,String target) //返回网址URL中名为target的图像
getAudioClip(URL base,String target)
//返回网址URL中名为target的声音对象
getParameter(String target ) //提取HTML文件中名为target的参数的值
同页Applet间的通信
在java.applet.Applet类中提供了如下方法得到当前运行页的环境上下文AppletContext对象。
public AppletContext getAppletContext();
通过AppletContext对象,可以得到当前小应用程序运行环境的信息。AppletContext是一个接口,其中定义了一些方法可以得到当前页的其它小应用程序,进而实现同页小应用程序之间的通信。
(1)得到当前运行页的环境上下文AppletContext对象
public AppletContext getAppletContext();
(2)取得名为name的Applet对象
public abstract Applet getApplet(String name);
(3)得到当前页中所有Applet对象
public abstract Enumeration getApplets();
例6.11
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Enumeration;
public class GetApplets extends Applet implemements ActionListener
{
private TextArea textArea; //声明一个TextArea
private String newline;
public void init() {
Button b=new Button("Click to call getApplets()");
b.addActionListener(this);
setLayout(new BorderLayout());
add("North",b);
textArea=new TextAred(5,40);
textArea.setEditable(false);
add("Center",textArea);
newline=System.getProperty("line,separator");
//取得系统当前的换行符
}
public void actionPerformed(ActionEvent event) {
/*Button b点击后的事件处理函数*/
printApplets();
}
public String getAppletInfo() {
return "GetApplets by Dong.li";
}
public void printApplets()}
Enumeration e=getAppletContext().getApplets();
/*得到当前网页所有的Applet对象*/
textArea.append("Results of getApplets():" + newline);
while(e.hasMoreElements()) {
Applet applet=(Applet) e.nextElement();
String info=((Applet)applet).getAppletInfo();
/*逐个取得当前网页Applet对象的信息*/
if (info!=null) {
textArea.append("-"+info+newline);
/*在textArea中输出网页所有Applet的信息*/
} else {
textArea.append("-"+applet.getClass().getName()+newline)
;
}
}
textArea.append("__________"+newline+newline);
}
}
|