JS脚本调用Applet的内部方法

在上一篇随笔中,讲述了如何将Applet放入到HTML页面,本篇将接着上次的内容,讲述JS如何如果调用Applet的内部方法,实现与Applet的交互。

例子非常简单,就是JS控制改变Applet的背景色。

首先,编译执行MyApplet.java,生成class文件。

View Code
 1 package Mystar;
 2 import java.applet.Applet;
 3 import java.awt.*;
 4 public class MyApplet extends Applet
 5 {
 6 
 7     private static final long serialVersionUID = 1L;
 8     private static Color [] Colors={Color.blue,Color.ORANGE,Color.BLACK,Color.BLUE,Color.CYAN,Color.DARK_GRAY,Color.GREEN,Color.PINK,Color.YELLOW};
 9     private static int index;
10     public void init()
11     {
12      index=0;
13      setBackground(Colors[index]);
14     }
15     public void paint(Graphics g)
16     { 
17       super.paint(g);
18       g.setColor(Color.RED);
19       g.drawString("Hello world!",30,60);
20       g.setColor(Color.red);
21       g.drawString("This is my first Applet code", 30, 80);
22     }
23     
24     public void resetMyApplet()
25     {    
26         if(++index==9)
27         index=0;
28         setBackground(Colors[index]);
29         super.paint(getGraphics());
30     }
31 }

当然你要保证Applet能够正确执行。

  接下来就是如何放入到jsp页面中(在上一篇已提到),编写JS脚本调用Applet的内部方法。

 

View Code
<%@ page language="java" contentType="text/html; charset=UTF-8"
    import="java.util.*,java.sql.ResultSet"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>

<title>JS调用Applet内部方法</title>
</head>
<body>
            
<applet alt="" id="my" name code="Mystar.MyApplet.class" height="250" width="250"> </applet> 
<br>
<input   type="submit"   name="Submit"   value="改变applet背景色"   onClick="kc()">    
<script   language="javascript">      
 function kc()  
 {      
  document.my.resetMyApplet();      
 }    
</script>

</body>
</html>
        

效果:

 

打开页面时背景是蓝色的,点击一次按钮后的效果。

posted @ 2013-01-10 16:07  方子格  阅读(1826)  评论(0编辑  收藏  举报