例如,现在对一个文件夹,点击右键,显示的功能列表为 共享,撤销共享。
这样的功能,java可以做出来吗?如何可以都需要哪些知识呢,有经验的大侠们,是否贴出个小例子,供着参考呢,谢谢..
------解决方案--------------------
- Java code
这篇文件仍然是在CSDN的java没有找到相关资料的情况下而写,希望这篇文章能帮各位兄弟省点时间。在java中使实现右键菜单十分简单,只需用到一个控件:PopupMenu.首先,需要声明一个PopupMenu对像。PopupMenu popupMenu1 = new PopupMenu();然后新建一些子菜单,这里我们使用建立三个菜单项MenuItem menuItem1 = new MenuItem();MenuItem menuItem2 = new MenuItem();MenuItem menuItem3 = new MenuItem();然后再出初化,并加入监听事件中:menuItem1.setLabel("菜单1");menuItem1.addActionListener(new java.awt.event.ActionListener() { //菜单1的事件监听public void actionPerformed(ActionEvent e) {menuItem1_actionPerformed(e); //菜单事件函数}});menuItem2.setLabel("菜单2");menuItem3.setLabel("菜单3");popupMenu1.add(menuItem1);popupMenu1.add(menuItem2);popupMenu1.add(menuItem3);//在this中加入popupMenu1add(popupMenu1);这时,菜单已经加进程序中了,现在我们需要做的就是在点击右键时显示。先在init中加入鼠标的单击事件,this.addMouseListener(new java.awt.event.MouseAdapter() {public void mousePressed(MouseEvent e) {this_mousePressed(e);}});再在this_mousePressed(e);中将菜单显示出来void this_mousePressed(MouseEvent e) {int mods=e.getModifiers();//鼠标右键if((mods&InputEvent.BUTTON3_MASK)!=0){//弹出菜单popupMenu1.show(this,e.getX(),e.getY());}}//菜单1事件void menuItem1_actionPerformed(ActionEvent e) {//菜单事件1}好了,讲到这里已经全部结束,是不是非常简单啊这里有一个继承Panel类的完整的例子import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Panel1 extends JPanel {PopupMenu popupMenu1 = new PopupMenu();MenuItem menuItem1 = new MenuItem();MenuItem menuItem2 = new MenuItem();MenuItem menuItem3 = new MenuItem();public Panel1() {try {jbInit();}catch(Exception ex) {ex.printStackTrace();}}void jbInit() throws Exception {this.setLayout(null);menuItem1.setLabel("菜单1");menuItem1.addActionListener(new java.awt.event.ActionListener() {public void actionPerformed(ActionEvent e) {menuItem1_actionPerformed(e);}});menuItem2.setLabel("菜单2");menuItem3.setLabel("菜单3");this.addMouseListener(new java.awt.event.MouseAdapter() {public void mousePressed(MouseEvent e) {this_mousePressed(e);}});popupMenu1.add(menuItem1);popupMenu1.add(menuItem2);popupMenu1.add(menuItem3);add(popupMenu1);}void this_mousePressed(MouseEvent e) {int mods=e.getModifiers();//鼠标右键if((mods&InputEvent.BUTTON3_MASK)!=0){//弹出菜单popupMenu1.show(this,e.getX(),e.getY());}}void menuItem1_actionPerformed(ActionEvent e) {//菜单事件}}