Take the 2-minute tour ×

How can I do to create a custom event and send it programmatically to a component?

E.g. If I had a JButton and wanted to create an ActionEvent or a MouseEvent and than send it as if an user had pressed on it which code I'd to use?

The following code not work:

JButton btn = new JButton("Click...");

MouseAdapter my = new MouseAdapter()
   public void mousePressed(MouseEvent e)
      area.setText("Button clicked!!!");

MouseEvent me = new MouseEvent(btn, MouseEvent.BUTTON1, 1, 0, 1, 1, 1, false);
share|improve this question
Generating an event is a bit nasty. Are you sure there isn't another solution that will solve your problem? In the case of the JButton you can call button.getModel().setPressed(true). –  Russ Hayward Sep 24 '10 at 11:48

2 Answers 2

For your specific example you can simply call AbstractButton#doClick.

If you need to create synthetic events for the general case, make sure fill in all fields that a real AWTEvent would have, since the event handlers may take them for granted.

share|improve this answer
Can you, please, post me a simple, working example of it? –  xdevel2000 Sep 27 '10 at 13:48
@xdevel2000: What specific event do you want to generate? –  Geoffrey Zheng Sep 27 '10 at 14:09
See stackoverflow.com/questions/3800840/… for an example. –  Geoffrey Zheng Sep 27 '10 at 14:50
Ok, I understand that I must use dispatchEvent on the component I want the event be sent. I tried to use it on a JButton but it does not work...look at the example I posted into the modified question. What's wrong? –  xdevel2000 Sep 28 '10 at 6:53
Aside from the obvious typo (btn.dispatchEvent(me) instead of my), your code works for me. –  Geoffrey Zheng Sep 29 '10 at 15:38

I think you can call the dispatchEvent method with the Event as an argument

share|improve this answer

Your Answer


