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()));

}

你可能感兴趣的:(swing)