• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Java » Swing » JPopupMenu in Java Swing Example
Next →
← Prev

JPopupMenu in Java Swing Example

By Dinesh Thakur

Using the JPopupMenu class, context-sensitive pop-up menus can be created, which are provided in most of today’s computer applications. These menus are used to provide options specific to the component for which the pop-up trigger event was generated. The pop-up trigger events occur when the right mouse button is either pressed or released. Program demonstrates how such a pop-up menu can be created.

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class PopupTest extends JFrame implements MouseListener
{
                 public JRadioButtonMenuItem items[];
                 String fonts[]={"Bold", "Italic", "Bold Italic"};
                 public String displaytext="This is a demonstrating popup menus,"+
                                                     "Please right click the mouse";
                 final JPopupMenu popupMenu;
                 public int index;
                 public PopupTest()
                 {
                         super("PopupMenu Example");
                         popupMenu=new JPopupMenu();
                         ItemHandler handler=new ItemHandler();
                         index=3;
                         ButtonGroup fontsGroup=new ButtonGroup();
                         items=new JRadioButtonMenuItem[3];
                         for(int i=0;i<items.length;i++)
                             {
                                  items[i] =new JRadioButtonMenuItem(fonts[i]);
                                  fontsGroup.add (items[i]);
                                  popupMenu.add(items[i]);
                                  items[i].addActionListener(handler);
                             }
                        getContentPane().setBackground(Color.white);
                        getContentPane().addMouseListener(this);
                        setSize(300,200);
                        show();
                }
                public void mousePressed(MouseEvent e)
                  {
                        checkForTriggerEvent(e);
                  }
                public void mouseReleased(MouseEvent e)
                 {
                        checkForTriggerEvent(e);
                 }
                 public void mouseMoved(MouseEvent e)
                 { }
                 public void mouseClicked(MouseEvent e)
                 { }
                 public void mouseEntered(MouseEvent e)
                 { }
                 public void mouseExited(MouseEvent e)
                 { }
                 private void checkForTriggerEvent(MouseEvent e)
                 {
                     if(popupMenu.isPopupTrigger(e))
                       {
                             popupMenu.show(e.getComponent(),e.getX() ,e.getY());
                       }
                 }
                 public void paint(Graphics g)
                 {
                       super.paint(g);
                       String fontname="Arial";
                       int type=Font.PLAIN;
                       int size=12;
                       Font font;
                       FontMetrics fm;
                       switch(index)
                               {
                                      case 0: type=type|Font.BOLD;
                                                 break;
                                      case 1: type=type|Font.ITALIC;
                                                 break;
                                      case 2: type=type|Font.BOLD|Font.ITALIC;
                                                 break;
                                      default:type=Font.PLAIN;
                                                 break;
                               }
                        font=new Font(fontname,type,size);
                        g.setFont(font);
                        fm=getFontMetrics(font);
                        int xloc=(getSize().width-fm.stringWidth (displaytext))/2;
                        int yloc=(getSize().height-fm.getHeight())/2;
                        g.drawString(displaytext,xloc,yloc);
                  }
                     public static void main(String args[])
                      {
                             PopupTest app=new PopupTest();
                             app.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                      }
                     private class ItemHandler implements ActionListener
                     {
                                  public void actionPerformed(ActionEvent e)
                                  {
                                        for(int i=0;i<items.length;i++)
                                            {
                                                  if(e.getSource() ==items[i])
                                                    {
                                                            index=i;
                                                            repaint();
                                                            return;
                                                    }
                                            }
                                   }
                       }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Before any of the radio button menu items are selected the text is displayed in plain font. If the Bold Italic menu item is selected, then the text displayed will be as follows:

                      JPopupMenu in Java Swing Example

When the user clicks the right mouse button on the Popup Test window, a JPopupMenu of fonts is displayed. If the user clicks one of the menu items that represent a font (that is, JRadioButtonMenultem) then the action Performed method of the class ItemHandler changes the font of the text displayed to the appropriate font. The constructor for the class Pop-up test defines the JPopupMenu.

                        final JPopupMenu popupMenu = new JPopupMenu();

In Program, the class Popup Test extends the class JFrame and implements the interface MouseListener. In this class, there is an inner class which implements the Item Listener interface to listen to the menu button-clicks. The methods mousePressed and mouseReleased are overridden to check for the pop-up-trigger event. Each method calls the private method checkForTriggerEvent to determine if the popup-trigger event occurs. The method isPopup Trigger returns the value true if the pop-up-trigger event has occurred. In that case, the show() method of JPopupMenu is invoked to display the pop-up menu. The first argument of the show() method specifies the origin component, whose position helps us determine where the pop-up menu will appear on the screen. The last two arguments are the x and y coordinates from the origin-component’s upper-left comer at which the pop-up menu should appear.

When a menu item is selected from the pop-up menu, the method actionPerformed() of the private inner class ItemHandler determines which object of JRadioButtonMenultem was selected : by the user and accordingly displays the text appropriate on the window.

Other than the ones listed above, the JPopupMenu class contains methods to set the invoker, label and size of the pop-up menu.

                    Constructors and methods in the jpopupMenu class.

 

Constructors and Methods

Description

JPopupMenu()

Constructs a new JPopupMenu object.

JPopupMenu(String str)

Constructs a new JPopupMenu object with the title specified by the parameter.

JMenultem add(Action action)

Appends a menu item that initiates the specified action to the end of the pop-up menu.

JMenultem add(Menultem menuitem)

Appends the specified menu item to the end of the pop-up menu.

void addPopupMenuListener(Popup MenuListener listener)

Adds a listener of PopupMenu class to the pop-up menu.

void addSeparator()

Adds or appends a new separator to the end of this menu.

Component getComponent()

Returns the name of the component of JPopupMenu.

Component getComponentAtlndex(int index)

Returns the jpopupMenu Component at the specified index.

int getComponentlndex(Component c)

Returns the index of the specified component in the JPopupMenu.

Component getinvoker()

Returns the component that invokes this pop-up menu.

String getLabel()

Returns the po-pup menu’s title.

void insert(Component component, int index)

Inserts or adds the specified component at the specified index for this pop-up menu.

void pack()

Lays out the container such that it uses the minimum space to display its contents.

void remove(Component component)

Removes the specified component from the pop-up menu

void remove(int index)

Remove the component at the specified index from the pop-up menu.

void show(Component component, int x, int y)

Displays the pop-up menu on the window.

You’ll also like:

  1. JList in Java Swing Example
  2. SpringLayout in Java Swing Example
  3. FocusListener in Java Swing Example
  4. CheckerBoard Java Swing Example
  5. Gradient in Java Swing Example
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

SQL Tutorials

SQL Tutorials

  • SQL - Home
  • SQL - Select
  • SQL - Create
  • SQL - View
  • SQL - Sub Queries
  • SQL - Update
  • SQL - Delete
  • SQL - Order By
  • SQL - Select Distinct
  • SQL - Group By
  • SQL - Where Clause
  • SQL - Select Into
  • SQL - Insert Into
  • SQL - Sequence
  • SQL - Constraints
  • SQL - Alter
  • SQL - Date
  • SQL - Foreign Key
  • SQL - Like Operator
  • SQL - CHECK Constraint
  • SQL - Exists Operator
  • SQL - Drop Table
  • SQL - Alias Syntax
  • SQL - Primary Key
  • SQL - Not Null
  • SQL - Union Operator
  • SQL - Unique Constraint
  • SQL - Between Operator
  • SQL - Having Clause
  • SQL - Isnull() Function
  • SQL - IN Operator
  • SQL - Default Constraint
  • SQL - Minus Operator
  • SQL - Intersect Operator
  • SQL - Triggers
  • SQL - Cursors

Advanced SQL

  • SQL - Joins
  • SQL - Index
  • SQL - Self Join
  • SQL - Outer Join
  • SQL - Join Types
  • SQL - Cross Join
  • SQL - Left Outer Join
  • SQL - Right Join
  • SQL - Drop Index
  • SQL - Inner Join
  • SQL - Datediff() Function
  • SQL - NVL Function
  • SQL - Decode Function
  • SQL - Datepart() Function
  • SQL - Count Function
  • SQL - Getdate() Function
  • SQL - Cast() Function
  • SQL - Round() Function

Other Links

  • SQL - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW