It is my understanding that one can handle events through Swing by adding a Listener (eg. a MouseListener) using a Component’s addXXXListener method.
Suppose I want, for whatever, to intercept ALL events that a Component (in my case, a JFrame) receives and do something generic with them eg. write my custom event dispatcher for whatever reason. One very cumbersome and slow way to do this would be to create a Listener class that listens for every single event and does something with them.
However, I found a better idea: I extended JFrame, and overrode processEvent(AWTEvent event) like so:
public class GameFrame extends JFrame
{
public GameFrame(int width, int height)
{
super();
//blah blah, stuff
setVisible(true);
}
//override processEvent which is called in Component class every time an event happens
@Override
public void processEvent(AWTEvent event)
{
System.out.println("override " + event);
//do whatever I want with my event here, then send it back up
doSomething(event);
super.processEvent(event);
}
}
The idea is that whenever an event happens on JFrame, processEvent will be called, and I’ll be able to get the event straight from there.
Unfortunately, the processEvent method is only being called with WindowEvents. MouseEvents and KeyEvents don’t seem to be working: when I run the code, the System.out.println only prints out WindowEvents.
I think I know the reason – because there are no MouseListeners in my code, Component doesn’t bother to call processEvent because there are no MouseListeners. So I could get this code to work if I created and added to JFrame a MouseListener, KeyListener…etc but this is no different from cumbersome and slow method I mentioned earlier.
So what can I do? Is there perhaps some other Component method that is called every time an event happens on the component, and which can be overriden in order to intercept all events on the Component directly from the horse’s mouth, without having to use Listeners?
It is because of the JFrame only support two type of Event. In JFrame.java, there is one line:
the solution is like below, change the behaviour of JFrame to force it listene to MouseEvent and other event you name (for exmaple: AWTEvent.MOUSE_MOTION_EVENT_MASK or MOUSE_WHEEL_EVENT_MASK).
The enableEvents() is in Component class, and it is protected method, so have to walk around by using reflection.