开发者

Swing send an event programmatically

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)开发者_运维技巧;


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜