Java如何确定是否显示JComboBox菜单?
本示例说明如何创建一个实现,PopupMenuListener以侦听JComboBox菜单可见,不可见或取消时的菜单。
package org.nhooo.example.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();
}
private void initialize() {
setSize(300, 300);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLayout(new FlowLayout(FlowLayout.LEFT));
Integer[] years = new Integer[] {2005, 2006, 2007, 2008, 2009, 2010};
JComboBox<Integer> comboBox = new JComboBox<>(years);
comboBox.setEditable(true);
//添加一个PopupMenu侦听器,它将监听通知
//来自组合框弹出部分的消息。
comboBox.addPopupMenuListener(new PopupMenuListener() {
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
//在弹出菜单变为可见之前调用此方法。
System.out.println("PopupMenuWillBecomeVisible");
}
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
//在弹出菜单不可见之前调用此方法
System.out.println("PopupMenuWillBecomeInvisible");
}
public void popupMenuCanceled(PopupMenuEvent e) {
//取消弹出菜单时调用此方法
System.out.println("PopupMenuCanceled");
}
});
getContentPane().add(comboBox);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ComboBoxPopupMenuListener().setVisible(true);
}
});
}
}