Reputation: 21364
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);
Upvotes: 1
Views: 4002
Reputation: 6640
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.
Upvotes: 2
Reputation: 11270
I think you can call the dispatchEvent
method with the Event as an argument
Upvotes: 0