I'm a little confused on where the action logic (what happens when a user selects a menu item from the popup) should be placed. Currently, I have it stored in a subclass of JPopupMenu, but it doesn't seem to call the event when I click on a menu item.

Subclass code:

public class MyPopupMenu extends JPopupMenu {
    JMenuItem item1;
    JMenuItem item2;
    
    public MyPopupMenu() {
        item1 = new JMenuItem("New Tab");
        item2 = new JMenuItem("Close Tab");
        
        add(item1);
        add(item2);
        
    }
    
    class myListener extends MouseAdapter {
        @Override
        public void mouseClicked(MouseEvent ev) {
            System.out.println("I've been clicked!");
        }
    }
}

I attached this to my JTabbedPane by calling the setComponentPopupMenumethod.

myTabPane.setComponentPopupMenu(myPopupMenu); 

This compiles OK. And it does show the popup menu as expected, but upon selecting one of the menu options in the popup, all is silent. No message gets displayed. Do I need to put it somewhere else?

有帮助吗?

解决方案

其他提示

Add MouseListner to your menu item

myListener myListener = new myListener();
item1.addMouseListener(myListener);
item2.addMouseListener(myListener);

Seems your approach is bit wrong. Please refer How to Use Menus

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top