Java Swing is registered as an event

In Java Swing, I can register a listener for a specific gui event as follows

guiElement.addMouseListener(myListener); 

but what if I want to automatically log all mouse events in my graphics application?
Should I register myListener for each item?
In other words, I'm looking for something like

 myListener.registerToEventType(MouseEvent.class) 

Any idea? Thanks you

+7
source share
3 answers

but what if I want to automatically log all mouse events in my graphics application?

@see AWTEventListener, there are mouse and key events

Should I register myListener for each item?

yes is better than redirecting, consuming, or using SwingUtilities to apply MouseEvents to blurry JComponets, the notification code may be longer than the anonymous listener added to each of the JComponents separatelly

+3
source

I think you cannot do this however you want. A possible approach is to use Action Commands as described in this.

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

This is just an example, but you get the idea.

+2
source

Try something like:

 Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() { @Override public void eventDispatched(AWTEvent event) { MouseEvent mouseEvent = (MouseEvent) event; System.out.println(mouseEvent.getPoint()); } }, AWTEvent.MOUSE_EVENT_MASK); 
+1
source

All Articles