事件处理Applet类从Container类继承了许多事件处理方法。Container类定义了几个方法,例如:processKeyEvent()和processMouseEvent(),用来处理特别类型的事件,还有一个捕获所有事件的方法叫做processEvent。 为了响应一个事件,applet必须重写合适的事件处理方法。 import java.awt.event.MouseListener; import java.awt.event.MouseEvent; import java.applet.Applet; import java.awt.Graphics; public class ExampleEventHandling extends Applet implements MouseListener { StringBuffer strBuffer; public void init() { addMouseListener(this); strBuffer = new StringBuffer(); addItem("initializing the apple "); } public void start() { addItem("starting the applet "); } public void stop() { addItem("stopping the applet "); } public void destroy() { addItem("unloading the applet"); } void addItem(String word) { System.out.println(word); strBuffer.append(word); repaint(); } public void paint(Graphics g) { //Draw a Rectangle around the applet's display area. g.drawRect(0, 0, getWidth() - 1, getHeight() - 1); //display the string inside the rectangle. g.drawString(strBuffer.toString(), 10, 20); } public void mouseEntered(MouseEvent event) { } public void mouseExited(MouseEvent event) { } public void mousePressed(MouseEvent event) { } public void mouseReleased(MouseEvent event) { } public void mouseClicked(MouseEvent event) { addItem("mouse clicked! "); } }
如下调用该applet: <html> <title>Event Handling</title> <hr> <applet code="ExampleEventHandling.class" width="300" height="300"> </applet> <hr> </html>
最开始运行,applet显示 "initializing the applet. Starting the applet.",然后你一点击矩形框,就会显示"mouse clicked" 。
显示图片applet能显示GIF,JPEG,BMP等其他格式的图片。为了在applet中显示图片,你需要使用java.awt.Graphics类的drawImage()方法。 如下实例演示了显示图片的所有步骤: import java.applet.*; import java.awt.*; import java.net.*; public class ImageDemo extends Applet { private Image image; private AppletContext context; public void init() { context = this.getAppletContext(); String imageURL = this.getParameter("image"); if(imageURL == null) { imageURL = "java.jpg"; } try { URL url = new URL(this.getDocumentBase(), imageURL); image = context.getImage(url); }catch(MalformedURLException e) { e.printStackTrace(); // Display in browser status bar context.showStatus("Could not load image!"); } } public void paint(Graphics g) { context.showStatus("Displaying image"); g.drawImage(image, 0, 0, 200, 84, null); g.drawString("www.javalicense.com", 35, 100); } }
如下调用该applet: <html> <title>The ImageDemo applet</title> <hr> <applet code="ImageDemo.class" width="300" height="200"> <param name="image" value="java.jpg"> </applet> <hr> </html>
|