2013-04-30 49 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);