How do I determine if the menu of JComboBox is displayed?

This example show how to create an implementation of PopupMenuListener for listening to when the JComboBox menu is visible, invisible or cancelled.

package org.kodejava.swing;

import javax.swing.*;
import javax.swing.event.PopupMenuListener;
import javax.swing.event.PopupMenuEvent;
import java.awt.*;

public class ComboBoxPopupMenuListener extends JFrame {
    public ComboBoxPopupMenuListener() {
        initialize();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(
                () -> new ComboBoxPopupMenuListener().setVisible(true));
    }

    private void initialize() {
        setSize(500, 500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new FlowLayout(FlowLayout.LEFT));

        Integer[] years = new Integer[]{
                2016, 2017, 2018, 2019, 2020,
                2021, 2022, 2023, 2024, 2025
        };

        JComboBox<Integer> comboBox = new JComboBox<>(years);
        comboBox.setEditable(true);

        // Adds a PopupMenu listener which will listen to notification
        // messages from the popup portion of the combo box.
        comboBox.addPopupMenuListener(new PopupMenuListener() {
            public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
                // This method is called before the popup menu becomes visible.
                System.out.println("PopupMenuWillBecomeVisible");
            }

            public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
                // This method is called before the popup menu becomes invisible
                System.out.println("PopupMenuWillBecomeInvisible");
            }

            public void popupMenuCanceled(PopupMenuEvent e) {
                // This method is called when the popup menu is canceled
                System.out.println("PopupMenuCanceled");
            }
        });

        getContentPane().add(comboBox);
    }
}
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.