popupmenudemo.java

来自「《java事件处理指南》一书的代码,好东西」· Java 代码 · 共 102 行

JAVA
102
字号
import javax.swing.*;import javax.swing.event.*;import java.awt.*;import java.awt.event.*;public class PopupMenuDemo extends JFrame {   private JLabel label;   private JPopupMenu menu;   private JTextField jtf;   public PopupMenuDemo()    {/*  A JPopupMenu is created with two menu items.  The JPopupMenu   *//*  registers a PopupMenuListener.                                 */      menu = new JPopupMenu("menu");      menu.add(new JMenuItem("open"));      menu.add(new JMenuItem("quit"));      menu.addPopupMenuListener(new PopupMenuHandler());      label = new JLabel("Menu");      label.setFont(new Font("Serif", Font.BOLD, 12));      label.setForeground(Color.black);      label.setBorder(BorderFactory.createEmptyBorder(20,20,20,20));      label.addMouseListener(new MouseHandler());      jtf = new JTextField(15);      jtf.setEditable(true);      JPanel centerPanel = new JPanel();      centerPanel.add(label);      getContentPane().add(centerPanel, BorderLayout.CENTER);      getContentPane().add(jtf, BorderLayout.SOUTH);      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);      setBounds(100, 100, 300, 200);      setVisible(true);   }/*  The PopupMenuListener is implemented as an inner class.   *//*  When a PopupMenuEvent is generated, it is sent to one     *//*  of the three listener methods.  The type of event is      *//*  printed inside a textfield at the bottom of the frame.    */   class PopupMenuHandler implements PopupMenuListener   {      public void popupMenuCanceled(PopupMenuEvent event)      {         jtf.setText("menu canceled");      }      public void popupMenuWillBecomeInvisible(PopupMenuEvent event)      {         jtf.setText("menu becoming invisible");      }      public void popupMenuWillBecomeVisible(PopupMenuEvent event)      {         jtf.setText("menu becoming visible");      }   }/*  The MouseListener is used to detect the popup menu trigger  *//*  When that happens, the popup menu is made visible.  All     *//*  three types of non-motion oriented MouseEvents are tested   *//*  because the popup menu trigger may be platform dependent.   */   class MouseHandler extends MouseAdapter   {      public void mousePressed(MouseEvent event)       {         testEvent(event);      }      public void mouseReleased(MouseEvent event)       {         testEvent(event);      }      public void mouseTyped(MouseEvent event)       {         testEvent(event);      }      private void testEvent(MouseEvent event)      {         if ( event.isPopupTrigger() )         {            menu.show(label, event.getX(), event.getY());         }      }   }   public static void main(String args[])    {      PopupMenuDemo demo = new PopupMenuDemo();   }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?