Java Swing How to - Highlight item in JComboBox popup








Question

We would like to know how to highlight item in JComboBox popup.

Answer

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.plaf.basic.BasicComboPopup;
// w  w w. j a v  a  2 s .c  o  m
public class Main extends JFrame {
  public Main() {
    String[] items = { "Item1", "Item2", "Item3", "Item4", "Item5" };
    JComboBox<String> comboBox = new JComboBox<>(items);
    add(comboBox);

    comboBox.addPopupMenuListener(new PopupMenuListener() {
      public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
        JComboBox<String> comboBox = (JComboBox<String>) e.getSource();
        BasicComboPopup popup = (BasicComboPopup) comboBox
            .getAccessibleContext().getAccessibleChild(0);
        JList list = popup.getList();
        list.setSelectedIndex(2);
      }

      public void popupMenuCanceled(PopupMenuEvent e) {
      }

      public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
      }

    });
  }

  public static void main(String[] args) {
    Main frame = new Main();
    frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}