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);
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024