如何在用户在 Java 中的 JComboBox 上单击右键时显示弹出菜单?
JComboBox 是 JComponent 类的子类,它显示一个 下拉列表 ,并向用户提供选项,我们一次只能选择一项。JComboBox 可以是 可编辑的或只读的。getSelectedItem() 方法 可用于从组合框中获取所选或输入的项目。当用户右键单击 JComboBox 时,我们可以通过实现 MouseListener 接口并需要重写 mouseReleased() 方法,从中调用弹出菜单。MouseEvent类的isPopupTrigger()方法可用于显示弹出菜单。
示例
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JComboBoxPopupTest extends JFrame { private JComboBox jcb; private JPopupMenu jpm; private JMenuItem mItem1, mItem2; public JComboBoxPopupTest() { setTitle("JComboBoxPopup Test"); setLayout(new FlowLayout()); jcb = new JComboBox(new String[] {"Item 1", "Item 2", "Item 3"}); jpm = new JPopupMenu(); mItem1 = new JMenuItem("Popup Item 1"); mItem2 = new JMenuItem("Popup Item 2"); jpm.add(mItem1); jpm.add(mItem2); ((JButton)jcb.getComponent(0)).addMouseListener(new MouseAdapter() { public void mouseReleased(MouseEvent me) { if (me.isPopupTrigger()) { jpm.show(jcb, me.getX(), me.getY()); } } }); add(jcb); setSize(400, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) throws Exception { new JComboBoxPopupTest(); } }
输出
广告