There's a section on Bringing Up a Popup Menu in the How to Use Menus article of The Java Tutorials which explains how to use the JPopupMenu
class.
The example code in the tutorial shows how to add MouseListener
s to the components which should display a pop-up menu, and displays the menu accordingly.
(The method you describe is fairly similar to the way the tutorial presents the way to show a pop-up menu on a component.)