Reputation: 37
I'm trying to integrate a Jmenu in my java application, but I'm struggled to retrieve the selected path of a selected Item.
I found a couples of examples using the class MenuSelectionManager as follows:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
public class selectedPath {
public static void main(final String args[]) {
JFrame frame = new JFrame("MenuSample Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
// File Menu, F - Mnemonic
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
menuBar.add(fileMenu);
// File->New, N - Mnemonic
JMenuItem newMenuItem = new JMenuItem("New");
fileMenu.add(newMenuItem);
newMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MenuElement[] eles = MenuSelectionManager.defaultManager().getSelectedPath();
System.out.println(eles.length);
for (MenuElement ele : eles) {
System.out.println(ele);
}
MenuSelectionManager.defaultManager().clearSelectedPath();
}
});
frame.setJMenuBar(menuBar);
frame.setSize(350, 250);
frame.setVisible(true);
}
}
but it didn't work as the MenuElement array is empty. Any suggestions?
Thanks
Upvotes: 0
Views: 664
Reputation: 47608
The problem is that MenuSelectionManager
is already cleared when your actionPerformed
is invoked.
The calls are put in that order:
msm.clearSelectedPath(); // msm is the MenuSelectionManager
menuItem.doClick(0); // This eventually triggers your actionPerformed
But the question is what are you trying to do with that? You obviously know on which JMenutItem
the click was performed (e.getSource()
returns the related JMenuItem
), and you can easily travel back up the component hierarchy to retrieve the complete path of the selected menu, so I wonder what you are trying to achieve with such code.
Upvotes: 2