Jmenu option onclick get Text

82 Views Asked by At

I have the following JMenu:

enter image description here

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?

1

There are 1 best solutions below

1
David Kroukamp On BEST ANSWER

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());  
    }
});