learning java AWT 右键菜单

import java.awt.*;
import java.awt.event.*;

public class SimpleMenu {
    private Frame f  = new Frame("test");
    private MenuBar mb = new MenuBar();
    Menu file  =  new Menu("file");
    Menu edit  =  new Menu("edit");

    PopupMenu pop = new PopupMenu();

    MenuItem crateItem = new MenuItem("create");
    MenuItem saveItem = new MenuItem("save");

    MenuItem exitItem = new MenuItem("exit",
            new MenuShortcut(KeyEvent.VK_X));

    CheckboxMenuItem autoWrap = new CheckboxMenuItem("autoWrap");

    MenuItem copyItem = new MenuItem("copy");
    MenuItem pasteItem = new MenuItem("paste");

    Menu format =  new Menu("format");
    /*ctrl + shift + / */
    MenuItem commentItem = new MenuItem("comment", new MenuShortcut(KeyEvent.VK_SLASH,true));

    MenuItem cancelItem = new MenuItem("cancelComment");
    private TextArea ta = new TextArea(6,40);

    public void init(){
        ActionListener menuListener = e -> {
          var cmd = e.getActionCommand();
          ta.append(" click " + cmd + " menu " + " \n ");
          if(cmd.equals("exit")){
              System.exit(0);
          }
        };

        commentItem.addActionListener(menuListener);
        exitItem.addActionListener(menuListener);

        pop.add(autoWrap);
        pop.addSeparator();
        pop.add(copyItem);
        pop.add(pasteItem);

        pop.add(new MenuItem("-"));
        pop.add(format);

        final Panel p = new Panel();
        p.setPreferredSize(new Dimension(300,160));
        p.add(pop);
        p.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                if (e.isPopupTrigger()){
                    pop.show(p, e.getX(), e.getY());
                }
            }
        });

//        file.add(crateItem);
//        file.add(saveItem);
//        file.add(exitItem);
//
//        edit.add(autoWrap);
//        edit.addSeparator();
//        edit.add(copyItem);
//        edit.add(pasteItem);

        format.add(commentItem);
        format.add(cancelItem);

//        edit.add(new MenuItem("-"));
//        edit.add(format);


//
//        mb.add(file);
//        mb.add(edit);

        f.add(p);


        f.setMenuBar(mb);
        f.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

        f.add(ta, BorderLayout.NORTH);
        f.pack();
        f.setVisible(true);

    }

    public static void main(String[] args) {
        new SimpleMenu().init();
    }


}

output:

posted @ 2019-08-01 13:34  嵌入式实操  阅读(305)  评论(0编辑  收藏  举报