I have the following JMenu:
So, i added the same mouseclicked event in each menu option, so when i click one of them, in the evt, i can get the text. On the event i have the following code:
private void menuMouseClicked(java.awt.event.MouseEvent evt) {
System.out.println(evt.getSource ());
}
Having this, each time i press a option, i get the output: .....javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],paintBorder=false,paintFocus=false,pressedIcon=,rolloverEnabled=false,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=Add]
So the thing that i want, is from the evt, get the Text that says in the case of the first option "Add". How can i do this?
Cast it to the JMenuItem
and call getText()
private void menuMouseClicked(java.awt.event.MouseEvent evt) {
JMenuItem menuItem = (JMenuItem) evt.getSource();
System.out.println(menuItem.getText());
}
You may want to also look into JMenuItem#addActionListener
. You can add an ActionListener
to a specific JMenuItem
and then use the same logic:
someMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JMenuItem menuItem = (JMenuItem) evt.getSource();
System.out.println(menuItem.getText());
}
});