使用适配器和内部类来处理事件

类别:Java 点击:0 评论:0 推荐:
刚才我们看到一个 BT  的例子,在实现 MouseListener 接口时必须要撰写处理每一个鼠标事件的方法。这里介绍 Adapter 。轻松点。

import java.applet.Applet;

import java.awt.*;

import java.awt.event.*;

 

public class MouseEventAdapterDemo extends Applet {

    BlankArea blankArea;

    TextArea textArea;

    static final int maxInt = java.lang.Integer.MAX_VALUE;

    String newline;

 

    public void init() {

        GridBagLayout gridbag = new GridBagLayout();

        GridBagConstraints c = new GridBagConstraints();

        setLayout(gridbag);

 

        c.fill = GridBagConstraints.BOTH;

        c.gridwidth = GridBagConstraints.REMAINDER;

        c.weightx = 1.0;

        c.weighty = 1.0;

 

        c.insets = new Insets(1, 1, 1, 1);

        blankArea = new BlankArea(new Color(0.98f, 0.97f, 0.85f));

        gridbag.setConstraints(blankArea, c);

        add(blankArea);

 

        c.insets = new Insets(0, 0, 0, 0);

        textArea = new TextArea(5, 20);

        textArea.setEditable(false);

        gridbag.setConstraints(textArea, c);

        add(textArea);

 

        //Register for mouse events on blankArea and applet (panel).

        blankArea.addMouseListener(new MyEvent());

        addMouseListener(new MyEvent());

 

        newline = System.getProperty("line.separator");

    }

 

    class MyEvent extends MouseAdapter {

        public void mousePressed(MouseEvent e) {

           saySomething("Mouse pressed; # of clicks: " + e.getClickCount(), e);

       }

 

       void saySomething(String eventDescription, MouseEvent e) {

           textArea.append(

               eventDescription

                  + " detected on "

                  + e.getComponent().getClass().getName()

                  + newline);

           textArea.setCaretPosition(maxInt); //hack to scroll to bottom

       }

    }

}

无须多说了。

本文地址:http://com.8s8s.com/it/it14947.htm