Search code examples
javaswingjcombobox

How do you make the popup menu of a JComboBox visible?


How do you make the popup menu of an editable JComboBox visible? When I enter any text in the JComboBox's textfield it should display its popup list items. Here is my code. I have added a KeyListener in which I invoke showPopup() and setPopupVisible(true). But it does nothing.

import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JComboBox;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class Test extends JFrame {

private JPanel contentPane;
private JComboBox comboBox;
private JTextField textField;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Test frame = new Test();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public Test() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);
    
    comboBox = new JComboBox(new Object[] {"Ester", "Jordi", "Jordina", "Jorge", "Sergi"});
    comboBox.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent arg0) {
            comboBox.showPopup();
            comboBox.setPopupVisible(true);
        }
    });
    comboBox.setEditable(true);
    comboBox.setBounds(10, 11, 414, 20);
    contentPane.add(comboBox);
}
}

Solution

  • I did some work and somehow made it work. But this is not the recommended way. Please add following code after

    comboBox = new JComboBox(new Object[] {"Ester", "Jordi", "Jordina", "Jorge", "Sergi"});

    Component[] comps = comboBox.getComponents();
    for(Component comp : comps){
        if(comp instanceof CellRendererPane){
            JComboBox co = (JComboBox) ((CellRendererPane)comp).getParent();
            co.getEditor().getEditorComponent().addKeyListener(new KeyAdapter()      {
                @Override
                public void keyPressed(KeyEvent arg0) {
                    comboBox.showPopup();
                    comboBox.setPopupVisible(true);
                }
            });
        }
    }
    

    This is working fine.But it's better to use decorator and have new components, also have a look into following article,

    JComboBox autocomplete