swing右键菜单

1.初始化要添加右键菜单的控件和右键菜单以及右键菜单下的项

private JList fileList = new JList(listModel);

private JPopupMenupopupMenu = new JPopupMenu();

private JMenuItem menuItem1 = new JMenuItem("移除");

private JMenuItem menuItem2 = new JMenuItem("添加");

 

2.将菜单项添加进菜单中

popupMenu.add(menuItem1);

popupMenu.add(menuItem2);

 

3.给菜单和菜单项添加鼠标和单击事件

该类实现接口ActionListener,MouseListener

fileList.addMouseListener(this);

menuItem.addActionListener(this);

 

4.该类实现接口中的方法

publicvoid mouseClicked(MouseEvent e){

    }

 

    publicvoid mousePressed(MouseEvent e) {

 

        selectIndex = fileList.locationToIndex(e.getPoint());

 

        // 获取鼠标点击的项

        fileList.setSelectedIndex(selectIndex);

 

        maybeShowPopup(e);

 

    }

 

    publicvoid mouseReleased(MouseEvent e) {

        maybeShowPopup(e);

    }

 

    // 弹出右键菜单菜单

    privatevoid maybeShowPopup(MouseEvent e) {

        if (e.isPopupTrigger() && fileList.getSelectedIndex() != -1)       {

 

            // 获取选择项的值

            Object selected = fileList.getModel().getElementAt(

                    fileList.getSelectedIndex());

 

            selectItem = selected;

            System.out.println(selected);

            popupMenu.show(e.getComponent(), e.getX(), e.getY());

        }

    }

 

    publicvoid mouseEntered(MouseEvent e) {

 

    }

 

    publicvoid mouseExited(MouseEvent e) {

 

}

 

 

// 如果选择了移除

    elseif (obj == menuItem1) {

        listModel.removeElement(selectItem);

        fileS.remove(new File(selectItem.toString()));

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值