Speaking Mouse to Hunt Down a Popup Menu

The mouse is one of the most abused input devices on today’s computers. Second to maybe the keyboard, it is essential for gathering input from the user. We tell it what to do but what if we stopped a second and had our application listen to it? I mean, REALLY listen to it and not just that listening you do when your favorite show is on TV and your girl is asking you about what you think of her 1023rd pair of designer shoes…. nodding your head as if you really cared. Could it tell us where to find tremendous wealth? Could it reveal the meaning of life? Could it decipher some NSA encryption algorithm to give us the ability to launch a fire sale like that on the latest Die Hard movie? Probably not… but it can tell you how to launch that bad ass popup you have waiting in the wind. I will show you how with some Java on this entry of the Programming Underground!

This example is pretty straight forward really. Make a JFrame, add a textbox, attach a mouselistener and have it show a popup object. Sound pretty easy? Well it is. The toughest part is actually remember all the steps. So below I will show you how to do it step by step. Let’s get started!

import javax.swing.*;
import java.awt.event.*;

public class MouseTesting extends JFrame {

	// Static popup variable so the application can see our popup.
	static JPopupMenu popup;

	public static void main(String args[]) {

		// Setup our swing JFrame and set its size.
		JFrame newFrame = new JFrame("Mouse Test");
		// Create an instance of JPopupMenu
		popup = new JPopupMenu();

		// Create a menu item and add it to the popup menu we just defined.
		JMenuItem menuItem = new JMenuItem("Popup Item 1");

		// Create a second menu item and add it to the menu we defined.
		menuItem = new JMenuItem("Popup Item 2");

		// Here we create a mouselistener using our class defined below.
		// Since PopupClass() implements the MouseListener interface, 
		// We can set it up as a MouseListener class. As far as Java knows
		// pListener is now an object which it knows has certain mouselistener
		// events it responds to.

		MouseListener pListener = new PopupClass();

		// Set a null layout and throw on a textfield. 
		// setBounds() can be used in a null layout to place the x, y, w, h dimensions
		// of a given control. 
		JTextField text1 = new JTextField();

		// Add our new listener to this field and finally add the field to the frame.

		// It's SHOW TIME!


	// Here we implement a static inner class (class within a class) and
	// make it extend from the MouseAdapter class. It implements just one
	// event but could implement more mouse events. 

	// It checks to see if a popup trigger has been detected which can be different
	// for each operating system. On windows it would be when we release the right button
	// of the mouse. 

	public static class PopupClass extends MouseAdapter {
		public void mouseReleased(MouseEvent e) {
			if (e.isPopupTrigger()) {
						popup.show(e.getComponent(), e.getX(), e.getY());

First of all, make sure you read through the code and read the in code comments if you haven’t already. The project here I have called “MouseTesting” and it does a few things. It has main() of course to start the program and setup a few GUI (Graphic User Interface) controls. If you are not familiar with Swing applications, I recommend you read up on that before continuing. The application assumes the programmer has a basic understanding of the controls like a JTextField and JPopupMenu.

In main we setup a JFrame and it also builds a popup menu for it. Building popups are not that big of a deal really. Create a popup menu instance variable, then create as many JMenuItem instances as you want. After you have passed the text you want the menu item to read, you add it to the JPopupMenu object you created.

Next thing we are going to do is create a mouse listener object. This object is responsible for listening to the mouse and handling its events. In our case above, we have opted to create a secondary “inner class” to be extended from MouseAdapter. MouseAdapter is a special class that implements several interfaces, one being MouseListener. It is used to create our own custom class that listens to whatever events we tell it to rather than having to implement every method of the interface (like we would have to do if we implemented MouseListener directly). Our class here implements only one method, the mouseReleased() method which handles when the user presses the right mouse key and lets go of it. Once the user does that, we check if the mouse event is attempting to trigger a popup. This is done by checking isPopupTrigger of the event.

Then on our JFrame we setup a JTextField. I have opted to use a null layout which allows me to place controls at a specific pixel coordinate and set the width and height of each control as I add it. Here I am placing the textfield in the upper left corner at coordinate 10, 10 and it has a width of 100 and a height of 20. After placing my control, I have to attach it to our mouse listening class. This is done using addMouseListener and passing it an instance of the class. Here I call the instance “pListener”. Notice it is of type MouseListener and is an instance of our inner class PopupClass. This attaches the mouse listening to the textfield. We add the textfield to the JFrame and show the JFrame.

So here is the series of steps….

1) The Jframe is created and we configure its size and any properties.
2) We then creates a JPopupMenu, some popup menu items and builds the menu.
3) We creates an instance of our mouse listening inner class that implements the MouseListener interface and handles the event when our right mouse key is released.
4) We create a JTextField control, configuring it for the upper left corner of the frame.
5) We attach the mouse listening to this new field. We could add it to other controls if we wanted to show the same popup for different controls.
6) We add the control to the frame
7) Show the frame.

Here is the series of events…

1) The user selects the text field and hits the right mouse button.
2) Java receives a messaging saying a right mouse button was clicked then released and passes the event to the class which handles mouse listening (aka PopupClass)
3) PopupClass then says “Do I have an event that handles a mouse click? no, do I have one that handles a mouse release? yes, ok, execute that code”
4) mouseReleased asks “Was this an event that was trying to trigger a popup? Yes, ok, call our popup menu’s show method to show the menu”
5) Menu is shown with all its items.

That is all there is. Step through the code, then the series of steps and series of events and hopefully you will see what is going on. The series of events should make some sense after reading the code and its in code comments.

Now your application is listening to your mouse and flushing out your popup menu! The mouse might be small, but it can pack quite a wallop if used correctly in your application. We trigger one popup menu here, but we could use it launch different popup menus for different controls, have it launch the same popup for all controls etc. Next time you are pressing the mouse, take a minute to thank your mouse for showing you the way.

Enjoy and thanks for reading this entry. 🙂

About The Author

Martyr2 is the founder of the Coders Lexicon and author of the new ebooks "The Programmers Idea Book" and "Diagnosing the Problem" . He has been a programmer for over 25 years. He works for a hot application development company in Vancouver Canada which service some of the biggest tech companies in the world. He has won numerous awards for his mentoring in software development and contributes regularly to several communities around the web. He is an expert in numerous languages including .NET, PHP, C/C++, Java and more.