event
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 theJComboBox
component with thePopupMenuListener
.
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; @Override public void popupMenuCanceled(PopupMenuEvent event) { } @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent event) { } @Override public void popupMenuWillBecomeVisible(PopupMenuEvent event) { if (!init) { JComboBox comBox = (JComboBox) event.getSource(); ComboBoxModel comboModel = new DefaultComboBoxModel(itemArray); comBox.setModel(comboModel); init = true; } } }; JComboBox jCombo = new JComboBox(); jCombo.addPopupMenuListener(popupMenuListener); jCombo.setMaximumRowCount(6); jCombo.setEditable(true); cPane.add(jCombo, BorderLayout.NORTH); jFrame.pack(); jFrame.setVisible(true); } }
This was an example on how to use PopupMenuListeners in Java.