KeyEvent.getSource() 和 KeyEvent.getComponent() 之间的区别

Difference between KeyEvent.getSource() and KeyEvent.getComponent()

KeyEvent.getSource()KeyEvent.getComponent() 有什么区别,什么时候使用哪个? 我正在使用 KeyEvents 创建一些 UI。 我必须看到有功能 KeyEvent.getSource() KeyEvent.getComponent() 并且很好奇什么时候使用哪个。 java api 的研究结果如下: getSource() 为 EventObject 继承,说明如下: "The object on which the Event initially occurred." getComponent() 继承自 ComponentEvent "Returns the originator of the event."

现在在我看来他们 return 同一个对象但类型不同。

因此问题是:这样正确吗?我应该使用哪一个?

来自here

getSource() is a method provided in the AWTEvent which is the abstract class for all the event classes. You call the getSource() method when you want to know what caused that action. This would be useful when you have an actionEvent that can be triggered by a button, a textfield or a menu item. You may want to know which item caused the action to fire and this call does that

此外,getComponent() 方法将 return 事件捕获的 Component 对象。因此,在查看是什么导致动作触发的情况下,使用什么来获取与之交互的对象并没有真正的区别。

来自对方的Javadoc:


getSource():

Object java.util.EventObject.getSource()

The object on which the Event initially occurred.

Returns:The object on which the Event initially occurred.


getComponent()

Component java.awt.event.ComponentEvent.getComponent()

Returns the originator of the event.

Returns:the Component object that originated the event, or null if the object is not a Component.


结论:

  1. getSource() returns 一个 Object,不能是 null,而 getComponent() returns 一个 Component,有时,如果 event instanceof Component == false,它 returns null

  2. 两者都需要转换成你想要的类型。当然,事先进行 instanceof 检查总是好的。但是,getSource() 可以让你的范围更广,施法时间可能会更长,但不能 null(据我所知)。

所以,使用 e.getSource() 总是更安全。

在 ComponentEvent 中,KeyEvent 的超类:

public Component getComponent() {
    return (source instanceof Component) ? (Component)source : null;
}

并且在 EventObject 中,ComponentEvent(和 KeyEvent)的 grandparent

protected transient Object  source;

public Object getSource() {
    return source;
}

源代码随JDK 1.8.0_121

提供

可以看出两者return一样Object(source)只要是一个Component,如果不是,getComponentreturns null.