本文主要是介绍java AWT PopupMenu(右键菜单),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
右键菜单使用PopupMenu对象表示,创建步骤如下:
(1)创建PopupMenu的实例。
(2)创建多个MenuItem的多个实例,依次将这些实例加入到PopupMenu中。
(3)将PopupMenu加入到目标组件中。
(4)为需要出现上下文菜单的组件编写鼠标监听器,当用户释放鼠标右键时弹出右键菜单。
package javaAWT;import java.awt.BorderLayout;
import java.awt.CheckboxMenuItem;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Menu;
import java.awt.MenuItem;
import java.awt.MenuShortcut;
import java.awt.Panel;
import java.awt.PopupMenu;
import java.awt.TextArea;
import java.awt.Desktop.Action;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;public class PopupMenuTest {private TextArea tArea = new TextArea(4, 50);private Frame frame = new Frame("PopupMenu");PopupMenu popupMenu = new PopupMenu();CheckboxMenuItem autoWrap = new CheckboxMenuItem("Auto Wrap");MenuItem copyItem = new MenuItem("Copy");MenuItem pasteItem = new MenuItem("Paste");Menu format = new Menu("Format");MenuItem commentItem = new MenuItem("Comment", new MenuShortcut(KeyEvent.VK_SLASH, true));MenuItem cancelItem = new MenuItem("Canecl");public void init() {ActionListener menuListener = new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubString cmd = e.getActionCommand();tArea.append("Clicked "+ cmd +" Menu " + "\n");if (cmd.equals("Cancel")) {System.exit(0);}}};commentItem.addActionListener(menuListener);// 为pop菜单添加菜单项popupMenu.add(autoWrap);popupMenu.addSeparator();popupMenu.add(copyItem);popupMenu.add(pasteItem);format.add(commentItem);format.add(cancelItem);popupMenu.add(new MenuItem("-"));popupMenu.add(format);final Panel panel = new Panel();panel.setPreferredSize(new Dimension(300, 160));panel.add(popupMenu);panel.addMouseListener(new MouseAdapter() {@Overridepublic void mouseReleased(MouseEvent e) {// TODO Auto-generated method stubsuper.mouseReleased(e);// 如果释放的是鼠标右键if (e.isPopupTrigger()) {popupMenu.show(panel, e.getX(), e.getY());}}});frame.add(panel);frame.add(tArea, BorderLayout.NORTH);frame.addWindowListener(new WindowAdapter() {@Overridepublic void windowClosing(WindowEvent e) {// TODO Auto-generated method stubsuper.windowClosing(e);System.exit(0);}});frame.pack();frame.setVisible(true);}public static void main(String[] args) {new PopupMenuTest().init();}
}
这篇关于java AWT PopupMenu(右键菜单)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!