问题描述:

When it comes to events, I definitely come from an ActionScript background. I am currently working on a project using Swing in which I need to dispatch an event from one object and capture the event in the parent, and I have no idea how to do it.

In ActionScript3, you can dispatch an event with a dispatchEvent call. For example, let's say I wanted to programmatically dispatch a mouseClick event (even though the mouse was not clicked) so that some other listener will activate. I can do that by using

dispatchEvent(MouseEvent.Click);

Once that gets called, the event will bubble up through it's parent objects until it hits the top, and event listeners can capture it on the way. (Technically it bubbles down and back up, but that's outside the scope of the question, I believe). So if I want to listen for that mouseClick event in the parent object, I would just add a listener like so:

parent.addEventListener(MouseEvent.Click, Function);

Which would capture that mouseClick and perform the Function.

That's how it works in ActionScript3. I'm trying to do something similar in Java, and there appears to be some big theory changes in how Java events work. How would I do the same thing in java? Specifically, how to I programmatically dispatch an event and capture that event in a parent object?

I have done my own research on the subject, and it has merely confused me further. I have looked at:

  • How do I programatically send ActionEvent to JButton?
  • Concurrency in Swing - The Event Dispatch Thread.
  • Events and listeners - How do you create a custom event?

网友答案:

For firing events programmatically, look at AbstractButton.doClick() if you are outside the button, or preferably AbstractButton.fireActionPerformed() in a subclass.

When developing components, the lack of bubbling means that each parent component needs to handle and redispatch child component events:

innerButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent buttonEvent) {
        MyEvent myEvent = ... // process buttonEvent
        fireMyEventHappened(myEvent);
    }
});
网友答案:

The Component class has a dispatchEvent(...) method, so you can create and dispatch an event to any component directly.

Or if you want to generate an OS event manually then you can use the Robot class and Java will do the dispatching of the event for you. In this case

相关阅读:
Top