Thursday, July 8, 2010

How to create pop-up menus in Java  


Pop-up menus are the menus that are displayed when a user clicks the right mouse button.They are sometimes also known as short-cut menus.
Short cut menus are very handy in cases where some functionality you want to provide like adding a help menu to all controls on right click.

Step for creating Pop-up menus:-

1.Create an object of the JPopupMenu class.
2.Create object of the Menu class for each menu you want to add on the menu bar.
3.Call the add() method of the JPopupMenu class to add each menu object to the pop-up menu.
4.Create objects of the JMenuItem or CheckboxMenuItem class for each item that you want to in the menu.
5.Call the add() method of the Menu class to add each item to its appropriate menu.

Example Source code:-

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

public class PopUpColorMenu
Component selectedComponent;

public PopUpColorMenu( ) {
JFrame frame = new JFrame("PopUpColorMenu v1.0");

final JPopupMenu colorMenu = new JPopupMenu("Color");

MouseListener mouseListener = new MouseAdapter( ) {
public void mousePressed(MouseEvent e) { checkPopup(e); }
public void mouseClicked(MouseEvent e) { checkPopup(e); }
public void mouseReleased(MouseEvent e) { checkPopup(e); }
private void checkPopup(MouseEvent e) {
if (e.isPopupTrigger( )) {
selectedComponent = e.getComponent( );, e.getX( ), e.getY( ));
frame.getContentPane( ).addMouseListener(mouseListener);

frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
private JMenuItem makeMenuItem(String label) {
JMenuItem item = new JMenuItem(label);
return item;

public static void main(String[] args) {
new PopUpColorMenu( );

What next?

You can also bookmark this post using your favorite bookmarking service:

Related Posts by Categories

Extension Factory Builder