假设我想右击鼠标时,能够自动弹出一个可以供你选择的面板选项,就像是菜单一样的条目,我该怎么实现这种功能呢?
有请高手指点迷津!
谢谢拉!

解决方案 »

  1.   

    创建一个JPopupMenu,添加你的菜单项,最后在鼠标事件处理方法里把他show出来。
      

  2.   

    package socket;import java.awt.*;
    import java.awt.event.*;import javax.swing.*;public class JComboBoxDemo extends JFrame{    String[] s={"西瓜","苹果","草莓","香蕉","葡萄"};
        JComboBox combo=new JComboBox(s);
        JPopupMenu popupMenu = new JPopupMenu();
        JMenuItem jadd = new JMenuItem("add");
        JMenuItem jremove = new JMenuItem("remove");
        
        public JComboBoxDemo(){
            super("JComboBoxDemo");
            this.setSize(200,200);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            Container c = this.getContentPane();
            c.setLayout(new FlowLayout(FlowLayout.LEADING));
            this.getContentPane().add(combo);
            JButton add = new JButton("add");
            JButton remove = new JButton("remove");
            add.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    combo.addItem("test");
                }
            });
            
            remove.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    combo.removeAllItems();
                }
            });
            
            jadd.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    combo.addItem("test");
                }
            });
            
            jremove.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    combo.removeAllItems();
                }
            });
            
            popupMenu.add(jadd);
            popupMenu.addSeparator();
            popupMenu.add(jremove);
            
            
            this.getContentPane().add(add);
            this.getContentPane().add(remove);
            this.addMouseListener(new MouseAdapter(){
                //添加右键菜单
                public void mouseReleased(MouseEvent e){
                    if (e.isPopupTrigger()) { 
                        popupMenu.show(e.getComponent(), e.getX(), e.getY()); 
                      } 
                }
            });
            this.setVisible(true);
        }
        
        public static void main(String[] args){
            new JComboBoxDemo();
        }
        
    }