简体   繁体   English

Java中的MouseMotionListener如何工作?

[英]How MouseMotionListener in java works?

I am getting confused how the MouseMotionListener is used behind the scenes 我对如何在后台使用MouseMotionListener感到困惑

  • It is an Interface inside java awt 它是java awt内部的接口
  • But here we are not calling the methods it defines but we implement it and describe our own definition 但是这里我们不调用它定义的方法,而是实现它并描述我们自己的定义

For example this is what i think interfaces do 例如,这就是我认为接口所做的

Interface A {
    method work();
}

class ConcreteA { class ConcreteA {

 method work(){ //implementation goes here } 

} }

then a client code can call to any class that implements the A interface and call its work method 然后客户代码可以调用实现A接口的任何类并调用其工作方法

classImplementingA.work()

But here we implement the MouseMotionListener and add our own defition to the methods it exposes MouseDragged, mouseMoved. 但是在这里,我们实现了MouseMotionListener,并向其公开MouseDragged,mouseMoved的方法中添加了自己的定义。

So i want to know 所以我想知道

Does internally java calls this interface methods in turn calling our defined methods OR something else Java是否在内部调用此接口方法,然后依次调用我们定义的方法或其他方法

ie java internal works like client code for this interface and we defined the behind the scene implementation. 即java内部工作类似于该接口的客户端代码,我们定义了后台实现。

So plz somebody show me how java is handling the mouse movements and making this interface work with it in an easy way. 因此,请有人向我展示java如何处理鼠标移动并使该接口以一种简单的方式使用。

Listeners in general are based on the observable/observer pattern. 侦听器通常基于可观察/观察者模式。

Let's take a simpler example: ActionListener . 让我们举一个简单的例子: ActionListener You want to "observe" a button. 您要“观察”按钮。 You are thus the observer, and the button is the observable. 因此,您是观察者,按钮是可观察的。 You create an instance of ActionListener , and thus override its actionPerformed method. 您创建一个ActionListener实例,从而覆盖其actionPerformed方法。 You then add this listener to the button. 然后,您将此侦听器添加到按钮。 And now, the button, each time it's clicked, will call back (notify) the listener by calling its actionPerformed method. 现在,每次单击该按钮时,将通过调用其actionPerformed方法来回调(通知)侦听器。

A MouseMotionListener uses the same principle: you create an instance of MouseMotionListener and add it to a Swing component. MouseMotionListener使用相同的原理:创建MouseMotionListener的实例并将其添加到Swing组件。 Then, each time the mouse is moved inside this component, the component calls back (notifies) the listener by calling one of its methods ( mouseDragged or mouseMoved , depending on whether a mouse button is pressed or not). 然后,每次将鼠标移到该组件内部时,该组件都会通过调用其方法之一( mouseDraggedmouseMoved ,取决于是否按下鼠标按钮)来回调(通知)侦听器。

So, yes, you're right. 所以,是的,你是对的。 The client of the interface, in this case, is not your own code, but the Swing components. 在这种情况下,接口的客户端不是您自己的代码,而是Swing组件。 They are the callers of the interface implementations you define. 它们是您定义的接口实现的调用方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM