Home  >  Article  >  Java  >  Java Advanced Tutorial: Event Handling

Java Advanced Tutorial: Event Handling

黄舟
黄舟Original
2016-12-27 11:37:061722browse

The Applet class inherits many event handling methods from the Container class. The Container class defines several methods, such as processKeyEvent() and processMouseEvent(), to handle special types of events. There is also a method that captures all events called processEvent.

In order to respond to an event, the applet must override the appropriate event handling method.

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! ");
    }
}

The above is the content of Java Advanced Tutorial: Event Processing. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn