- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can we implement right click menu using JPopupMenu in Java?
A JPopupMenu appears anywhere on the screen when a right mouse button is clicked.
JPopupMenu
- A popup menu is a free-floating menu which associates with an underlying component called the invoker.
- Most of the time, a popup menu is linked to a specific component to display context-sensitive choices.
- In order to create a popup menu, we can use the JPopupMenu class., we can add the JMenuItem to popup menu like a normal menu.
- To display the popup menu, we can call the show() method, normally popup menu is called in response to a mouse event.
Example
import java.awt.event.*; import java.awt.*; import javax.swing.*; public class JPopupMenuTest extends JFrame { private JPopupMenu popup; public JPopupMenuTest() { setTitle("JPopupMenu Test"); Container contentPane = getContentPane() ; popup = new JPopupMenu(); // add menu items to popup popup.add(new JMenuItem("Cut")); popup.add(new JMenuItem("Copy")); popup.add(new JMenuItem("Paste")); popup.addSeparator(); popup.add(new JMenuItem("SelectAll")); contentPane.addMouseListener(new MouseAdapter() { public void mouseReleased(MouseEvent me) { showPopup(me); // showPopup() is our own user-defined method } }) ; setSize(375, 250); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } void showPopup(MouseEvent me) { if(me.isPopupTrigger()) popup.show(me.getComponent(), me.getX(), me.getY()); } public static void main(String args[]) { new JPopupMenuTest(); } }
Output
- Related Articles
- How can we create a JPopupMenu with a sub menu in Java?
- How can we Implement a Stack using Queue in Java?
- How can we Implement a Queue using Stack in Java?\n
- How can we show a popup menu when the user right-clicks on a JComboBox in Java?
- How can we implement a JToggleButton in Java?
- How can we implement editable JComboBox in Java?
- How can we implement transparent JDialog in Java?
- How can we implement a JSON array using Streaming API in Java?
- How can we implement Flow API using Publisher-Subscriber in Java 9?
- How can we implement different borders using the BorderFactory in Java?\n
- How can we implement a splash screen using JWindow in Java?\n
- How can we implement a moving text using a JLabel in Java?
- How to automate menu box/pop up of right click in Python Selenium?
- How to add custom button to the right click/context menu in Excel?
- How to add a custom right-click menu to a webpage in JavaScript?

Advertisements