7

在 Java Swing 中,我可以为某个 gui 事件注册一个监听器,如下所示

guiElement.addMouseListener(myListener);

但是如果我想自动注册到我的 GUI 应用程序中的所有鼠标事件呢?
我应该将 myListener 注册到每个元素吗?
换句话说,我正在寻找的是

myListener.registerToEventType(MouseEvent.class)

任何想法?
谢谢

4

3 回答 3

3

但是如果我想自动注册到我的 GUI 应用程序中的所有鼠标事件呢?

@see AWTEventListener,有鼠标和按键事件

我应该将 myListener 注册到每个元素吗?

是比重定向、使用或使用 SwingUtilities 将 MouseEvents 应用到被删除的 JComponet 更好,注意代码可能比单独添加到每个 JComponents 的匿名侦听器更长

于 2013-04-30T09:56:31.853 回答
2

我认为你不能按照你想要的方式那样做。Action Commands如本答案所述,一种可能的方法是使用。

JButton hello = new JButton("Hello");
hello.setActionCommand(Actions.HELLO.name());
hello.addActionListener(instance);
frame.add(hello);

JButton goodbye = new JButton("Goodbye");
goodbye.setActionCommand(Actions.GOODBYE.name());
goodbye.addActionListener(instance);
frame.add(goodbye);



 ...
  }

@Override
public void actionPerformed(ActionEvent evt) {
if (evt.getActionCommand() == Actions.HELLO.name()) {
   JOptionPane.showMessageDialog(null, "Hello");
   } 
else if (evt.getActionCommand() == Actions.GOODBYE.name()) {
   JOptionPane.showMessageDialog(null, "Goodbye");
   }
} 

这只是一个例子,但你明白了。

于 2013-04-30T09:56:18.453 回答
1

尝试类似:

Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {

        @Override
        public void eventDispatched(AWTEvent event) {
            MouseEvent mouseEvent = (MouseEvent) event;
            System.out.println(mouseEvent.getPoint());
        }
    }, AWTEvent.MOUSE_EVENT_MASK);
于 2013-04-30T19:28:12.157 回答