How can we show a popup menu when the user right-clicks on a JComboBox in Java?


A JComboBox is a subclass of JComponent class that displays a drop-down list and gives users options that we can select one and only one item at a time. A JComboBox can be editable or read-only. A getSelectedItem() method can be used to get the selected or entered item from a combo box. We can invoke a popup menu from a JComboxBox when the user right-clicks on it by implementing a MouseListener interface and need to override the mouseReleased() method. The method isPopupTrigger() of MouseEvent class can be used to show a popup menu.

Example

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JComboBoxPopupTest extends JFrame {
   private JComboBox jcb;
   private JPopupMenu jpm;
   private JMenuItem mItem1, mItem2;
   public JComboBoxPopupTest() {
      setTitle("JComboBoxPopup Test");
      setLayout(new FlowLayout());
      jcb = new JComboBox(new String[] {"Item 1", "Item 2", "Item 3"});
      jpm = new JPopupMenu();
      mItem1 = new JMenuItem("Popup Item 1");
      mItem2 = new JMenuItem("Popup Item 2");    
      jpm.add(mItem1);
      jpm.add(mItem2);
      ((JButton)jcb.getComponent(0)).addMouseListener(new MouseAdapter() {
         public void mouseReleased(MouseEvent me) {
            if (me.isPopupTrigger()) {
               jpm.show(jcb, me.getX(), me.getY());
            }
         }
      });
      add(jcb);
      setSize(400, 300);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String[] args) throws Exception {
      new JComboBoxPopupTest();
   }
}

Output

Updated on: 10-Feb-2020

306 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements