------------定义一个事件类------------------
import java.util.EventObject;
public class DoorEvent extends EventObject {
private String doorState = "";
public DoorEvent(Object source, String doorState) {
super(source);
this.doorState = doorState;
}
public void setDoorState(String doorState) {
this.doorState = doorState;
}
public String getDoorState() {
return this.doorState;
}
}
--------------定义事件监听器------------
import java.util.EventListener;
public interface DoorListener extends EventListener {//这个EventListener接口中没有方法。
public void doorEvent(DoorEvent event);
}
-------------------接口的实现类1-------------------
public class DoorListener1 implements DoorListener {
@Override
public void doorEvent(DoorEvent event) {
if (event.getDoorState() != null && event.getDoorState().equals("open")) {
System.out.println("1 opened");
} else {
System.out.println("1 closed");
}
}
}
--------------------接口的实现类2--------------------
public class DoorListener2 implements DoorListener {
@Override
public void doorEvent(DoorEvent event) {
if (event.getDoorState() != null && event.getDoorState().equals("open")) {
System.out.println("2 opened");
} else {
System.out.println("2 closed");
}
}
}
------------------------产生事件的源类,可以想成是Button类,在它上面点击下会产生事件-----------------------------
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
public class DoorManager {
private Collection<DoorListener> listeners;
public void addDoorListener(DoorListener listener) {
if (listeners == null) {
listeners = new HashSet<DoorListener>();
}
listeners.add(listener);
}
public void removeDoorListener(DoorListener listener) {
if (listeners == null)
return;
listeners.remove(listener);
}
protected void fireWorkspaceOpened() {
if (listeners == null)
return;
DoorEvent event = new DoorEvent(this, "open");
notifyListeners(event);
}
protected void fireWorkspaceClosed() {
if (listeners == null)
return;
DoorEvent event = new DoorEvent(this, "close");
notifyListeners(event);
}
private void notifyListeners(DoorEvent event) {
Iterator<DoorListener> iter = listeners.iterator();
while (iter.hasNext()) {
DoorListener listener = iter.next();
listener.doorEvent(event);
}
}
}
-----------------------测试程序------------------------------
public class DoorMain {
public static void main(String[] args) {
DoorManager manager = new DoorManager();
manager.addDoorListener(new DoorListener1());
manager.addDoorListener(new DoorListener2());
manager.fireWorkspaceOpened();//这个可以想像成我们点击了Button.即触发了事件
System.out.println("============");
manager.fireWorkspaceClosed();//这个可以想像成我们点击了Button..即触发了事件
}
}
--------------------输出结果------------------
2 opened
1 opened
============
2 closed
1 closed
------------------最后我们再来看看理论吧!------------------------------
java中的事件机制的参与者有3种角色:
1.event object:事件状态对象,用于listener的相应的方法之中,作为参数,一般存在与listerner的方法之中
2.event source:具体的事件源,比如说,你点击一个button,那么button就是event source,要想使button对某些事件进行响应,你就需要注册特定的listener。
3.event listener:具体的对监听的事件类,当它监听到event object产生的时候,它就调用相应的方法,进行处理。
先看看jdk提供的event包:
public interface EventListener:所有事件侦听器接口必须扩展的标记接口。
public class EventObject extends Object implements Serializable
所有事件状态对象都将从其派生的根类。 所有 Event 在构造时都引用了对象 "source",在逻辑上认为该对象是最初发生有关 Event 的对象。
在Java2处理事件时,没有采用dispatchEvent()-postEvent()-handleEvent()方式,采用了监听器类,每个事件类都有相关联的监听器接口。事件从事件源到监听者的传递是通过对目标监听者对象的Java方法调用进行的。
对每个明确的事件的发生,都相应地定义一个明确的Java方法。这些方法都集中定义在事件监听者(EventListener)接口中,这个接口要继承 java.util.EventListener。 实现了事件监听者接口中一些或全部方法的类就是事件监听者。
伴随着事件的发生,相应的状态通常都封装在事件状态对象中,该对象必须继承 自java.util.EventObject。事件状态对象作为单参传递给应响应该事件的监听者方法中。发出某种特定事件的事件源的标识是:遵从规定的 设计格式为事件监听者定义注册方法,并接受对指定事件监听者接口实例的引用。
首先问个问题:您熟悉java.util.EventObject 和java.util.EventListener两个类以及他们已有的子类吗?
如果你已经能够熟练使用jdk为我们提供的事件监听器,并且很熟悉 MouseEvent, KeyEvent, WindowEvent等等这些jdk为我们准备好的事件,那么想必你对java的事件机制已经有所理解。但是也许你还是觉得虽然用起来没什么问题,但是 原理还是有些糊涂,那么下面我们再进一步自己实现这些事件和监听器,即自定义事件。
其实自定义事件在java中很有用处,我们有的时候想让自己的程序产生一个事 件,但有不希望(或者不可能)用鼠标,键盘之类的输入设备进行操作,比如你写一个应用程序,在这个程序中一旦收到邮件就对邮件进行相关处理,对于“收到邮 件”这个事件,jdk中就没有定义。对于这样的事件,以及对于这样的事件的监听器,我们只能自己动手完成了。
---------------------------对照一下,java图形化编程时的事件处理----------------------------------我们只要实现自己的Listener,及往事件源中注册监听器,就行。事件类由jdk为我们提供。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
class SimpleListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String buttonName = e.getActionCommand();
if (buttonName.equals("按钮1"))
System.out.println("按钮1 被点击");
}
}
public class ActionTest {
private static JFrame frame;
private static JPanel myPanel;
private JButton button1;
public ActionTest() {
myPanel = new JPanel();
button1 = new JButton("按钮1");
SimpleListener ourListener = new SimpleListener();
button1.addActionListener(ourListener);
myPanel.add(button1);
}
public static void main(String s[]) {
ActionTest gui = new ActionTest();
frame = new JFrame("Simple1");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.getContentPane().add(myPanel);
frame.pack();
frame.setVisible(true);
}
}
---------------------下面我们来看看jdk中的这些类的实现吧-----------------------------
事件类
public class ActionEvent extends AWTEvent {//稍后再看看AWTEvent类。
/**
* The shift modifier. An indicator that the shift key was held
* down during the event.
*/
public static final int SHIFT_MASK = Event.SHIFT_MASK;
/**
* The control modifier. An indicator that the control key was held
* down during the event.
*/
public static final int CTRL_MASK = Event.CTRL_MASK;
/**
* The meta modifier. An indicator that the meta key was held
* down during the event.
*/
public static final int META_MASK = Event.META_MASK;
/**
* The alt modifier. An indicator that the alt key was held
* down during the event.
*/
public static final int ALT_MASK = Event.ALT_MASK;
/**
* The first number in the range of ids used for action events.
*/
public static final int ACTION_FIRST = 1001;
/**
* The last number in the range of ids used for action events.
*/
public static final int ACTION_LAST = 1001;
/**
* This event id indicates that a meaningful action occured.
*/
public static final int ACTION_PERFORMED = ACTION_FIRST; //Event.ACTION_EVENT
/**
* The nonlocalized string that gives more details
* of what actually caused the event.
* This information is very specific to the component
* that fired it.
* @serial
* @see #getActionCommand
*/
String actionCommand;
/**
* Timestamp of when this event occurred. Because an ActionEvent is a high-
* level, semantic event, the timestamp is typically the same as an
* underlying InputEvent.
*
* @serial
* @see #getWhen
*/
long when;
/**
* This represents the key modifier that was selected,
* and is used to determine the state of the selected key.
* If no modifier has been selected it will default to
* zero.
*
* @serial
* @see #getModifiers
*/
int modifiers;
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = -7671078796273832149L;
/**
* Constructs an <code>ActionEvent</code> object.
* <p>
* This method throws an
* <code>IllegalArgumentException</code> if <code>source</code>
* is <code>null</code>.
* A <code>null</code> <code>command</code> string is legal,
* but not recommended.
*
* @param source The object that originated the event
* @param id An integer that identifies the event.
* For information on allowable values, see
* the class description for {@link ActionEvent}
* @param command A string that may specify a command (possibly one
* of several) associated with the event
* @throws IllegalArgumentException if <code>source</code> is null
* @see #getSource()
* @see #getID()
* @see #getActionCommand()
*/
public ActionEvent(Object source, int id, String command) {
this(source, id, command, 0);
}
/**
* Constructs an <code>ActionEvent</code> object with modifier keys.
* <p>
* This method throws an
* <code>IllegalArgumentException</code> if <code>source</code>
* is <code>null</code>.
* A <code>null</code> <code>command</code> string is legal,
* but not recommended.
*
* @param source The object that originated the event
* @param id An integer that identifies the event.
* For information on allowable values, see
* the class description for {@link ActionEvent}
* @param command A string that may specify a command (possibly one
* of several) associated with the event
* @param modifiers The modifier keys down during event
* (shift, ctrl, alt, meta).
* Passing negative parameter is not recommended.
* Zero value means that no modifiers were passed
* @throws IllegalArgumentException if <code>source</code> is null
* @see #getSource()
* @see #getID()
* @see #getActionCommand()
* @see #getModifiers()
*/
public ActionEvent(Object source, int id, String command, int modifiers) {
this(source, id, command, 0, modifiers);
}
/**
* Constructs an <code>ActionEvent</code> object with the specified
* modifier keys and timestamp.
* <p>
* This method throws an
* <code>IllegalArgumentException</code> if <code>source</code>
* is <code>null</code>.
* A <code>null</code> <code>command</code> string is legal,
* but not recommended.
*
* @param source The object that originated the event
* @param id An integer that identifies the event.
* For information on allowable values, see
* the class description for {@link ActionEvent}
* @param command A string that may specify a command (possibly one
* of several) associated with the event
* @param modifiers The modifier keys down during event
* (shift, ctrl, alt, meta).
* Passing negative parameter is not recommended.
* Zero value means that no modifiers were passed
* @param when A long that gives the time the event occurred.
* Passing negative or zero value
* is not recommended
* @throws IllegalArgumentException if <code>source</code> is null
* @see #getSource()
* @see #getID()
* @see #getActionCommand()
* @see #getModifiers()
* @see #getWhen()
*
* @since 1.4
*/
public ActionEvent(Object source, int id, String command, long when,
int modifiers) {
super(source, id);
this.actionCommand = command;
this.when = when;
this.modifiers = modifiers;
}
/**
* Returns the command string associated with this action.
* This string allows a "modal" component to specify one of several
* commands, depending on its state. For example, a single button might
* toggle between "show details" and "hide details". The source object
* and the event would be the same in each case, but the command string
* would identify the intended action.
* <p>
* Note that if a <code>null</code> command string was passed
* to the constructor for this <code>ActionEvent</code>, this
* this method returns <code>null</code>.
*
* @return the string identifying the command for this event
*/
public String getActionCommand() {
return actionCommand;
}
/**
* Returns the timestamp of when this event occurred. Because an
* ActionEvent is a high-level, semantic event, the timestamp is typically
* the same as an underlying InputEvent.
*
* @return this event's timestamp
* @since 1.4
*/
public long getWhen() {
return when;
}
/**
* Returns the modifier keys held down during this action event.
*
* @return the bitwise-or of the modifier constants
*/
public int getModifiers() {
return modifiers;
}
/**
* Returns a parameter string identifying this action event.
* This method is useful for event-logging and for debugging.
*
* @return a string identifying the event and its associated command
*/
public String paramString() {
String typeStr;
switch(id) {
case ACTION_PERFORMED:
typeStr = "ACTION_PERFORMED";
break;
default:
typeStr = "unknown type";
}
return typeStr + ",cmd="+actionCommand+",when="+when+",modifiers="+
KeyEvent.getKeyModifiersText(modifiers);
}
}
AWTEvent类:
public abstract class AWTEvent extends EventObject {//看到了吧。还是从EventObject来的。
private static final PlatformLogger log = PlatformLogger.getLogger("java.awt.AWTEvent");
private byte bdata[];
/**
* The event's id.
* @serial
* @see #getID()
* @see #AWTEvent
*/
protected int id;
/**
* Controls whether or not the event is sent back down to the peer once the
* source has processed it - false means it's sent to the peer; true means
* it's not. Semantic events always have a 'true' value since they were
* generated by the peer in response to a low-level event.
* @serial
* @see #consume
* @see #isConsumed
*/
protected boolean consumed = false;
/*
* The event's AccessControlContext.
*/
private transient volatile AccessControlContext acc =
AccessController.getContext();
/*
* Returns the acc this event was constructed with.
*/
final AccessControlContext getAccessControlContext() {
if (acc == null) {
throw new SecurityException("AWTEvent is missing AccessControlContext");
}
return acc;
}
transient boolean focusManagerIsDispatching = false;
transient boolean isPosted;
/**
* Indicates whether this AWTEvent was generated by the system as
* opposed to by user code.
*/
private transient boolean isSystemGenerated;
/**
* The event mask for selecting component events.
*/
public final static long COMPONENT_EVENT_MASK = 0x01;
/**
* The event mask for selecting container events.
*/
public final static long CONTAINER_EVENT_MASK = 0x02;
/**
* The event mask for selecting focus events.
*/
public final static long FOCUS_EVENT_MASK = 0x04;
/**
* The event mask for selecting key events.
*/
public final static long KEY_EVENT_MASK = 0x08;
/**
* The event mask for selecting mouse events.
*/
public final static long MOUSE_EVENT_MASK = 0x10;
/**
* The event mask for selecting mouse motion events.
*/
public final static long MOUSE_MOTION_EVENT_MASK = 0x20;
/**
* The event mask for selecting window events.
*/
public final static long WINDOW_EVENT_MASK = 0x40;
/**
* The event mask for selecting action events.
*/
public final static long ACTION_EVENT_MASK = 0x80;
/**
* The event mask for selecting adjustment events.
*/
public final static long ADJUSTMENT_EVENT_MASK = 0x100;
/**
* The event mask for selecting item events.
*/
public final static long ITEM_EVENT_MASK = 0x200;
/**
* The event mask for selecting text events.
*/
public final static long TEXT_EVENT_MASK = 0x400;
/**
* The event mask for selecting input method events.
*/
public final static long INPUT_METHOD_EVENT_MASK = 0x800;
/**
* The pseudo event mask for enabling input methods.
* We're using one bit in the eventMask so we don't need
* a separate field inputMethodsEnabled.
*/
final static long INPUT_METHODS_ENABLED_MASK = 0x1000;
/**
* The event mask for selecting paint events.
*/
public final static long PAINT_EVENT_MASK = 0x2000;
/**
* The event mask for selecting invocation events.
*/
public final static long INVOCATION_EVENT_MASK = 0x4000;
/**
* The event mask for selecting hierarchy events.
*/
public final static long HIERARCHY_EVENT_MASK = 0x8000;
/**
* The event mask for selecting hierarchy bounds events.
*/
public final static long HIERARCHY_BOUNDS_EVENT_MASK = 0x10000;
/**
* The event mask for selecting mouse wheel events.
* @since 1.4
*/
public final static long MOUSE_WHEEL_EVENT_MASK = 0x20000;
/**
* The event mask for selecting window state events.
* @since 1.4
*/
public final static long WINDOW_STATE_EVENT_MASK = 0x40000;
/**
* The event mask for selecting window focus events.
* @since 1.4
*/
public final static long WINDOW_FOCUS_EVENT_MASK = 0x80000;
/**
* WARNING: there are more mask defined privately. See
* SunToolkit.GRAB_EVENT_MASK.
*/
/**
* The maximum value for reserved AWT event IDs. Programs defining
* their own event IDs should use IDs greater than this value.
*/
public final static int RESERVED_ID_MAX = 1999;
// security stuff
private static Field inputEvent_CanAccessSystemClipboard_Field = null;
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = -1825314779160409405L;
static {
/* ensure that the necessary native libraries are loaded */
Toolkit.loadLibraries();
if (!GraphicsEnvironment.isHeadless()) {
initIDs();
}
AWTAccessor.setAWTEventAccessor(
new AWTAccessor.AWTEventAccessor() {
public void setPosted(AWTEvent ev) {
ev.isPosted = true;
}
public void setSystemGenerated(AWTEvent ev) {
ev.isSystemGenerated = true;
}
public boolean isSystemGenerated(AWTEvent ev) {
return ev.isSystemGenerated;
}
public AccessControlContext getAccessControlContext(AWTEvent ev) {
return ev.getAccessControlContext();
}
public byte[] getBData(AWTEvent ev) {
return ev.bdata;
}
public void setBData(AWTEvent ev, byte[] bdata) {
ev.bdata = bdata;
}
});
}
private static synchronized Field get_InputEvent_CanAccessSystemClipboard() {
if (inputEvent_CanAccessSystemClipboard_Field == null) {
inputEvent_CanAccessSystemClipboard_Field =
(Field)java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public Object run() {
Field field = null;
try {
field = InputEvent.class.
getDeclaredField("canAccessSystemClipboard");
field.setAccessible(true);
return field;
} catch (SecurityException e) {
if (log.isLoggable(PlatformLogger.FINE)) {
log.fine("AWTEvent.get_InputEvent_CanAccessSystemClipboard() got SecurityException ", e);
}
} catch (NoSuchFieldException e) {
if (log.isLoggable(PlatformLogger.FINE)) {
log.fine("AWTEvent.get_InputEvent_CanAccessSystemClipboard() got NoSuchFieldException ", e);
}
}
return null;
}
});
}
return inputEvent_CanAccessSystemClipboard_Field;
}
/**
* Initialize JNI field and method IDs for fields that may be
* accessed from C.
*/
private static native void initIDs();
/**
* Constructs an AWTEvent object from the parameters of a 1.0-style event.
* @param event the old-style event
*/
public AWTEvent(Event event) {
this(event.target, event.id);
}
/**
* Constructs an AWTEvent object with the specified source object and type.
*
* @param source the object where the event originated
* @param id the event type
*/
public AWTEvent(Object source, int id) {
super(source);
this.id = id;
switch(id) {
case ActionEvent.ACTION_PERFORMED:
case ItemEvent.ITEM_STATE_CHANGED:
case AdjustmentEvent.ADJUSTMENT_VALUE_CHANGED:
case TextEvent.TEXT_VALUE_CHANGED:
consumed = true;
break;
default:
}
}
/**
* Retargets an event to a new source. This method is typically used to
* retarget an event to a lightweight child Component of the original
* heavyweight source.
* <p>
* This method is intended to be used only by event targeting subsystems,
* such as client-defined KeyboardFocusManagers. It is not for general
* client use.
*
* @param newSource the new Object to which the event should be dispatched
* @since 1.4
*/
public void setSource(Object newSource) {
if (source == newSource) {
return;
}
Component comp = null;
if (newSource instanceof Component) {
comp = (Component)newSource;
while (comp != null && comp.peer != null &&
(comp.peer instanceof LightweightPeer)) {
comp = comp.parent;
}
}
synchronized (this) {
source = newSource;
if (comp != null) {
ComponentPeer peer = comp.peer;
if (peer != null) {
nativeSetSource(peer);
}
}
}
}
private native void nativeSetSource(ComponentPeer peer);
/**
* Returns the event type.
*/
public int getID() {
return id;
}
/**
* Returns a String representation of this object.
*/
public String toString() {
String srcName = null;
if (source instanceof Component) {
srcName = ((Component)source).getName();
} else if (source instanceof MenuComponent) {
srcName = ((MenuComponent)source).getName();
}
return getClass().getName() + "[" + paramString() + "] on " +
(srcName != null? srcName : source);
}
/**
* Returns a string representing the state of this <code>Event</code>.
* This method is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not be
* <code>null</code>.
*
* @return a string representation of this event
*/
public String paramString() {
return "";
}
/**
* Consumes this event, if this event can be consumed. Only low-level,
* system events can be consumed
*/
protected void consume() {
switch(id) {
case KeyEvent.KEY_PRESSED:
case KeyEvent.KEY_RELEASED:
case MouseEvent.MOUSE_PRESSED:
case MouseEvent.MOUSE_RELEASED:
case MouseEvent.MOUSE_MOVED:
case MouseEvent.MOUSE_DRAGGED:
case MouseEvent.MOUSE_ENTERED:
case MouseEvent.MOUSE_EXITED:
case MouseEvent.MOUSE_WHEEL:
case InputMethodEvent.INPUT_METHOD_TEXT_CHANGED:
case InputMethodEvent.CARET_POSITION_CHANGED:
consumed = true;
break;
default:
// event type cannot be consumed
}
}
/**
* Returns whether this event has been consumed.
*/
protected boolean isConsumed() {
return consumed;
}
/**
* Converts a new event to an old one (used for compatibility).
* If the new event cannot be converted (because no old equivalent
* exists) then this returns null.
*
* Note: this method is here instead of in each individual new
* event class in java.awt.event because we don't want to make
* it public and it needs to be called from java.awt.
*/
Event convertToOld() {
Object src = getSource();
int newid = id;
switch(id) {
case KeyEvent.KEY_PRESSED:
case KeyEvent.KEY_RELEASED:
KeyEvent ke = (KeyEvent)this;
if (ke.isActionKey()) {
newid = (id == KeyEvent.KEY_PRESSED?
Event.KEY_ACTION : Event.KEY_ACTION_RELEASE);
}
int keyCode = ke.getKeyCode();
if (keyCode == KeyEvent.VK_SHIFT ||
keyCode == KeyEvent.VK_CONTROL ||
keyCode == KeyEvent.VK_ALT) {
return null; // suppress modifier keys in old event model.
}
// no mask for button1 existed in old Event - strip it out
return new Event(src, ke.getWhen(), newid, 0, 0,
Event.getOldEventKey(ke),
(ke.getModifiers() & ~InputEvent.BUTTON1_MASK));
case MouseEvent.MOUSE_PRESSED:
case MouseEvent.MOUSE_RELEASED:
case MouseEvent.MOUSE_MOVED:
case MouseEvent.MOUSE_DRAGGED:
case MouseEvent.MOUSE_ENTERED:
case MouseEvent.MOUSE_EXITED:
MouseEvent me = (MouseEvent)this;
// no mask for button1 existed in old Event - strip it out
Event olde = new Event(src, me.getWhen(), newid,
me.getX(), me.getY(), 0,
(me.getModifiers() & ~InputEvent.BUTTON1_MASK));
olde.clickCount = me.getClickCount();
return olde;
case FocusEvent.FOCUS_GAINED:
return new Event(src, Event.GOT_FOCUS, null);
case FocusEvent.FOCUS_LOST:
return new Event(src, Event.LOST_FOCUS, null);
case WindowEvent.WINDOW_CLOSING:
case WindowEvent.WINDOW_ICONIFIED:
case WindowEvent.WINDOW_DEICONIFIED:
return new Event(src, newid, null);
case ComponentEvent.COMPONENT_MOVED:
if (src instanceof Frame || src instanceof Dialog) {
Point p = ((Component)src).getLocation();
return new Event(src, 0, Event.WINDOW_MOVED, p.x, p.y, 0, 0);
}
break;
case ActionEvent.ACTION_PERFORMED:
ActionEvent ae = (ActionEvent)this;
String cmd;
if (src instanceof Button) {
cmd = ((Button)src).getLabel();
} else if (src instanceof MenuItem) {
cmd = ((MenuItem)src).getLabel();
} else {
cmd = ae.getActionCommand();
}
return new Event(src, 0, newid, 0, 0, 0, ae.getModifiers(), cmd);
case ItemEvent.ITEM_STATE_CHANGED:
ItemEvent ie = (ItemEvent)this;
Object arg;
if (src instanceof List) {
newid = (ie.getStateChange() == ItemEvent.SELECTED?
Event.LIST_SELECT : Event.LIST_DESELECT);
arg = ie.getItem();
} else {
newid = Event.ACTION_EVENT;
if (src instanceof Choice) {
arg = ie.getItem();
} else { // Checkbox
arg = Boolean.valueOf(ie.getStateChange() == ItemEvent.SELECTED);
}
}
return new Event(src, newid, arg);
case AdjustmentEvent.ADJUSTMENT_VALUE_CHANGED:
AdjustmentEvent aje = (AdjustmentEvent)this;
switch(aje.getAdjustmentType()) {
case AdjustmentEvent.UNIT_INCREMENT:
newid = Event.SCROLL_LINE_DOWN;
break;
case AdjustmentEvent.UNIT_DECREMENT:
newid = Event.SCROLL_LINE_UP;
break;
case AdjustmentEvent.BLOCK_INCREMENT:
newid = Event.SCROLL_PAGE_DOWN;
break;
case AdjustmentEvent.BLOCK_DECREMENT:
newid = Event.SCROLL_PAGE_UP;
break;
case AdjustmentEvent.TRACK:
if (aje.getValueIsAdjusting()) {
newid = Event.SCROLL_ABSOLUTE;
}
else {
newid = Event.SCROLL_END;
}
break;
default:
return null;
}
return new Event(src, newid, Integer.valueOf(aje.getValue()));
default:
}
return null;
}
/**
* Copies all private data from this event into that.
* Space is allocated for the copied data that will be
* freed when the that is finalized. Upon completion,
* this event is not changed.
*/
void copyPrivateDataInto(AWTEvent that) {
that.bdata = this.bdata;
// Copy canAccessSystemClipboard value from this into that.
if (this instanceof InputEvent && that instanceof InputEvent) {
Field field = get_InputEvent_CanAccessSystemClipboard();
if (field != null) {
try {
boolean b = field.getBoolean(this);
field.setBoolean(that, b);
} catch(IllegalAccessException e) {
if (log.isLoggable(PlatformLogger.FINE)) {
log.fine("AWTEvent.copyPrivateDataInto() got IllegalAccessException ", e);
}
}
}
}
that.isSystemGenerated = this.isSystemGenerated;
}
void dispatched() {
if (this instanceof InputEvent) {
Field field = get_InputEvent_CanAccessSystemClipboard();
if (field != null) {
try {
field.setBoolean(this, false);
} catch(IllegalAccessException e) {
if (log.isLoggable(PlatformLogger.FINE)) {
log.fine("AWTEvent.dispatched() got IllegalAccessException ", e);
}
}
}
}
}
} // class AWTEvent
-------------------------------------------
看看监听器吧。
package java.awt.event;
import java.util.EventListener;
/**
* The listener interface for receiving action events.
* The class that is interested in processing an action event
* implements this interface, and the object created with that
* class is registered with a component, using the component's
* <code>addActionListener</code> method. When the action event
* occurs, that object's <code>actionPerformed</code> method is
* invoked.
*
* @see ActionEvent
* @see <a href="http://java.sun.com/docs/books/tutorial/post1.0/ui/eventmodel.html">Tutorial: Java 1.1 Event Model</a>
*
* @author Carl Quinn
* @since 1.1
*/
public interface ActionListener extends EventListener {//注意EventListener这是一个标记接口,同有java.io.Serializable接口也是标记接口
/**
* Invoked when an action occurs.
*/
public void actionPerformed(ActionEvent e);//这个方法是子接口定义的。
}
---------------------------------------
最后我们来看看事件源类吧。图形化编程中很很多,AWT,SWING中。找个最常见的,简单的。Button.java
public class Button extends Component implements Accessible {
.....
/**
* The action to be performed once a button has been
* pressed. This value may be null.
* @serial
* @see #getActionCommand()
* @see #setActionCommand(String)
*/
String actionCommand;
transient ActionListener actionListener;
......
public synchronized void addActionListener(ActionListener l) {
if (l == null) {
return;
}
actionListener = AWTEventMulticaster.add(actionListener, l);
newEventsOnly = true;
}
..............
public synchronized void removeActionListener(ActionListener l) {
if (l == null) {
return;
}
actionListener = AWTEventMulticaster.remove(actionListener, l);
}
....
中间好多代码省略了,因为那不是我们关心的。
---------------------------
看到这文章有用,就请回复一下,谢谢。