tags:

views:

52

answers:

2

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!!!");
   }
};
btn.addMouseListener(my);

MouseEvent me = new MouseEvent(btn, MouseEvent.BUTTON1, 1, 0, 1, 1, 1, false);
btn.dispatchEvent(my);
A: 

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

barjak
+1  A: 

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.

Geoffrey Zheng
Can you, please, post me a simple, working example of it?
xdevel2000
@xdevel2000: What specific event do you want to generate?
Geoffrey Zheng
See http://stackoverflow.com/questions/3800840/sending-keypresses-to-jtextfield for an example.
Geoffrey Zheng
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
Aside from the obvious typo (`btn.dispatchEvent(me)` instead of `my`), your code works for me.
Geoffrey Zheng