you have to add MouseListener to JMenuItems
add proper listener to use Swing Action, ActionListener for JMenuItems, read Oracle tutorial for working code example
Where do you store the logic for a JPopupMenu?
-
30-07-2022 - |
Вопрос
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 setComponentPopupMenu
method.
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
Не связан с StackOverflow