PopupMenuListener example

With this tutorial we shall show you how use PopupMenuListener interface in Java. You can use this listener to monitor your popup menus by overriding certain methods that fire up when a specific event concerning the popup menu occurs.

All you have to do in order to use a PopupMenuListener is:

  • Create an new JComboBox
  • Create a new PopupMenuListner
  • Override the methods that correspond to the events you want to monitor, e.g popupMenuCanceled, popupMenuWillBecomeInvisible, popupMenuWillBecomeVisible. Every time an event occurs in this popup menu the respective method will be executed.
  • Finally use addPopupMenuListener to register the JComboBox component with the PopupMenuListener.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.desktop;

import java.awt.BorderLayout;
import java.awt.Container;

import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;

public class PopupMenuListenerExample {

    public static void main(String args[]) {

  JFrame jFrame = new JFrame();

  Container cPane = jFrame.getContentPane();

  final String itemArray[] = {"One", "Two", "Three"};

  PopupMenuListener popupMenuListener = new PopupMenuListener() {

boolean init = false;


public void popupMenuCanceled(PopupMenuEvent event) {



public void popupMenuWillBecomeInvisible(PopupMenuEvent event) {



public void popupMenuWillBecomeVisible(PopupMenuEvent event) {

    if (!init) {

  JComboBox comBox = (JComboBox) event.getSource();

  ComboBoxModel comboModel = new DefaultComboBoxModel(itemArray);


  init = true;




  JComboBox jCombo = new JComboBox();




  cPane.add(jCombo, BorderLayout.NORTH);



This was an example on how to use PopupMenuListeners in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Notify of

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

Inline Feedbacks
View all comments
Back to top button