Java Swing How to - Put JComboBox on a JPopupMenu








Question

We would like to know how to put JComboBox on a JPopupMenu.

Answer

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
//from   www.j  a va  2s.com
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPopupMenu;

public class Main {

  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setSize(400, 400);
    frame.setVisible(true);
    String[] list = { "1", "2", "3", "4", };
    JComboBox<String> comb = new JComboBox<>(list);
    final JPopupMenu pop = new JPopupMenu();
    pop.add(comb);
    frame.addMouseListener(new MouseAdapter() {

      @Override
      public void mousePressed(MouseEvent e) {
        System.out.println("mousePressed");
        pop.show(e.getComponent(), e.getX(), e.getY());
      }
    });
  }
}