Java JMenu 动作监听器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9862165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JMenu ActionListener
提问by clankfan1
I was wondering if can you test to see if a JMenu (not JMenuItem) has been clicked. I tried adding an ActionListener to it but it doesn't seem to recognize it. I just need it to preform an action when the JMenu button is pressed so that I can change the JMenuItems for that menu befor it opens. All work arrounds to get this result are welcome too!
我想知道您是否可以测试以查看是否已单击 JMenu(而不是 JMenuItem)。我尝试向它添加一个 ActionListener ,但它似乎无法识别它。我只需要它在按下 JMenu 按钮时执行一个操作,以便我可以在打开该菜单之前更改该菜单的 JMenuItems。也欢迎所有获得此结果的工作!
Thanks
谢谢
采纳答案by mKorbel
- for
JMenu
useMenuListener
- 供
JMenu
使用MenuListener
code
代码
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class ActionExample {
public ActionExample() {
JMenu menu = new JMenu("Menu");
menu.setMnemonic(KeyEvent.VK_M);
menu.addMenuListener(new SampleMenuListener());
JMenu menu1 = new JMenu("Tool");
menu1.setMnemonic(KeyEvent.VK_T);
menu1.addMenuListener(new SampleMenuListener());
JFrame f = new JFrame("ActionExample");
JMenuBar mb = new JMenuBar();
mb.add(menu);
mb.add(menu1);
f.setJMenuBar(mb);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
ActionExample actionExample = new ActionExample();
}
});
}
}
class SampleMenuListener implements MenuListener {
@Override
public void menuSelected(MenuEvent e) {
System.out.println("menuSelected");
}
@Override
public void menuDeselected(MenuEvent e) {
System.out.println("menuDeselected");
}
@Override
public void menuCanceled(MenuEvent e) {
System.out.println("menuCanceled");
}
}
- for
JMenuItem
use only ButtonModel
- 对于
JMenuItem
只使用ButtonModel的
回答by Antonio1996
With an instance of JMenu you can't add an ActionListener, only with JMenuItem you can do it.
对于 JMenu 的实例,您无法添加 ActionListener,只有使用 JMenuItem 才能添加。