Re: Detect when menu is chosen in JMenu
wx wrote:
I'd like to implement a menu with JMenu which has submenus. I'd like
to be able to click on an item or choose it with the keyboard with
enter or accelerator. This applies to both leaf menu items (without
submenus), but I'd also like to be able to choose JMenus (which have
submenus) and perform some action in that case. How to detect when a
JMenu is chosen? I tried adding an ActionListener, but that did not
work. I can implement mouse listener and key listener, but is there an
unified way to get "menu chosen" event, regardless of the method the
menu item has been chosen? I.e. is there something similar to
ItemListener, with the difference that the event should be fired when
the menu was actually chosen (e.g. mouse click, keyboard enter), not
only selected (e.g. mouse over, keyboard arrows)?
Here is one simple way of doing that. There is one side effect of using
mnemonic and that is that if you select the top level menu with a
mnemonic then the next level will also be selected. That may be L&F
specific I don't know but it is the case on Win XP.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class test99 extends JFrame implements ActionListener, MenuListener {
public test99() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar mb = new JMenuBar();
setJMenuBar(mb);
JMenu m1 = new JMenu("one");
m1.setMnemonic(KeyEvent.VK_O);
m1.addMenuListener(this);
JMenu s1 = new JMenu("sub one");
s1.setMnemonic(KeyEvent.VK_S);
s1.addMenuListener(this);
JMenuItem i1 = new JMenuItem("item one");
i1.setMnemonic(KeyEvent.VK_I);
i1.addActionListener(this);
JMenuItem i2 = new JMenuItem("item two");
i2.setMnemonic(KeyEvent.VK_T);
i2.addActionListener(this);
mb.add(m1);
m1.add(s1);
s1.add(i1);
s1.add(i2);
setSize(400,300);
setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
System.out.println(ae.getActionCommand());
}
public void menuCanceled(MenuEvent me) {
}
public void menuDeselected(MenuEvent me) {
}
public void menuSelected(MenuEvent me) {
System.out.println(((JMenu)(me.getSource())).getText());
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new test99();
}
});
}
}
--
Knute Johnson
email s/nospam/knute2008/
--
Posted via NewsDemon.com - Premium Uncensored Newsgroup Service
------->>>>>>http://www.NewsDemon.com<<<<<<------
Unlimited Access, Anonymous Accounts, Uncensored Broadband Access