Swing以编程方式发送事件 [英] Swing send an event programmatically

查看:217
本文介绍了Swing以编程方式发送事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建自定义事件并以编程方式发送到
组件?

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

例如。如果我有一个 JButton ,并且想要创建一个 ActionEvent 或一个 MouseEvent 而不是发送它为
如果用户按下我将使用哪个代码?

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?

以下代码不起作用: p>

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);


推荐答案

对于您的具体示例,您可以简单地调用 AbstractButton#doClick

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

如果您需要为一般情况创建合成事件,请确保填写所有字段, AWTEvent 将会有,因为事件处理程序可能会认为它们是理所当然的。

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.

这篇关于Swing以编程方式发送事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆