Saturday, 21 June 2008

JPopupMenu and ActionEvent's getSource( ) Method

When handling an event from a Java Swing component you would most likely implement the ActionListener interface and be able to get the source of the event from the ActionEvent's getSource() property. Not so if the event was triggered by a JPopupMenu. The type of the source of an ActionEvent is actually JPopupMenu$1 which seems to be a private inner class of JPopupMenu. The hack round this is pretty simple but not obvious because JPopupmenu$1 isn't documented anywhere.

JPopupMenu$1 extends Component and its parent is the JPopupMenu that you wanted in the first place so all you have to do is cast it and call getParent().

No comments: