Applet類從Container類繼承了許多事件處理方法。Container類定義了幾個方法,例如:processKeyEvent()和processMouseEvent(),用來處理特別類型的事件,還有一個捕獲所有事件的方法叫做processEvent。
為了響應(yīng)一個事件,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! "); } }
如下調(diào)用該applet:
最開始運行,applet顯示 "initializing the applet. Starting the applet.",然后你一點擊矩形框,就會顯示"mouse clicked" 。
2015職稱計算機考試書PowerPoint2007中 .. 定價:¥45 優(yōu)惠價:¥42 更多書籍 | |
2015年全國職稱計算機考試教材(2007模 .. 定價:¥225 優(yōu)惠價:¥213 更多書籍 |