Programming Examples

Are you a Programmer or Application Developer or a DBA? Take a cup of coffee, sit back and spend few minutes here :)

JPopupMenu Display on Right Click

1. Introduction JPopupMenu

We know a menu contains one or more menu items. We also saw how to display a menu from the Menubar in one of our examples. The menu can be displayed at mouse cursor location as well. Java provides a class called JPopupMenu which one can use to display a context menu at the mouse cursor location. The show method of the JPopupMenu takes (x, y) location and displays the pop-up menu at that location.

2. About the Context Menu Example

We will create an example as shown below:

Java Swing JPopupMenu Example
Java Swing JPopupMenu Example

Our example is a JFrame Window which can display a Context Menu. A context menu will appear at the click location of the mouse when user right clicks anywhere in the form except the title bar. The displayed menu will not have any title and it contains three menu items in it.

3. Create JPopupMenu

First, we create a JFrame which will be the parent for the JPopupMenu. Because the parent will display the context menu, the child will get closed when the user closes the Parent. In our case, JFrame is the parent and Context Menu, which we will display in the coming section is its child. So, when a user closes the Parent, it will close the Context Menu if it is already displaying. Since we want to display the context menu on a mouse right click location, our parent should implement the MouseListener. Below is the code:

After setting-up the parent (JFrame), we declare a Java Swing JPopupMenu as a class member. Refer code snippet 03 below:

Code Snippet 04 creates an instance of the JPopupMenu and then adds three sample menu items to it. This is the same as how we prepared JMenu by adding JMenuItem to it. Once context menu is ready, snippet 05 registers the JFrame window to receive mouse events. Because, we need to display our context menu when the user right clicks on the JFrame parent.

4. Display JPopupMenu

Our JFrame class implements MouseListener. It provides dummy implementations for all but mousePressed handler. Mouse-Pressed handler checks whether the user clicked the right mouse button or not. When it knows the user clicked the right-mouse button, the handler calls the show method of the JPopupMenu. First param is the parent as displaying JPopupMenu needs as parent. Second and third params tell the (x, y) location for displaying context menu. Below is the handler code for mousePressed:

5. Youtube Demo – Display Context Menu

JPopupMenu Example – Demo & Code Implementation

6. Code Reference

6.1 MainEntry.java

6.2 SwingPopupMenuExample.java

Categories: Swing

Tags: , , , ,

Do you like this Example? Please comment about it for others!!

This site uses Akismet to reduce spam. Learn how your comment data is processed.