2013-04-30 55 views
7

在的Java Swing我可以按如下的Java Swing寄存器事件类型

guiElement.addMouseListener(myListener); 

但听众注册到一定GUI事件,如果我想自动注册到我的GUI应用程序的所有鼠标事件是什么?
我应该注册myListener到每个元素?
在我所期待的。换句话说是一样的东西

myListener.registerToEventType(MouseEvent.class) 

任何想法?
谢谢

+0

*“注册所有鼠标事件”*为什么对鼠标事件感兴趣?通常我会为“ActionListener”提供一个'MouseListener'。 – 2013-04-30 09:55:12

+0

MouseListener只是一个例子,这个问题适用于所有类型的事件 – mottalrd 2013-04-30 10:04:21

+0

**为什么对事件感兴趣?**现在增加*更多*词,而不是更少。我不喜欢玩'20个问题'来获取基本信息。 – 2013-04-30 10:05:54

回答

2

我认为你不能这样做,你想要的方式。可能的方法是使用Action Commands,如在answer中所解释的。

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

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

3

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

@see AWTEventListener所,有鼠标&关键事件

我要注册myListener的每一个元素?

是比重定向,消耗或使用SwingUtilities类的应用MouseEvents到derised JComponets更好,通知代码,可能是长于annonymous监听器添加到每个JComponents的separatelly

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