Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Using ItemListener on a JMenu

 
Cory Twibell
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have the following:


<code>
JMenu menu = new JMenu("File");
menu.addItemListener( new ItemListener()
{
public void itemStateChanged( ItemEvent e )
{
JMenu m = (JMenu)e.getItem();
if ( e.getStateChange() == ItemEvent.SELECTED )
{
if ( !valid() ) //error checks a text field
m.setPopupMenuVisible( false );
}
}
} );
</code>


The popup menu still shows. Is JMenu class overriding my call to the popup menu? Is there a different way to do this? Maybe using a different listener?
Thanks
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not sure exactly what you are trying to do, but maybe you just need to use an ActionListener for each MenuItem rather than an ItemListener for the Menu.
HTH
Layne
 
Cory Twibell
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've tried an ActionListener, but the JMenu doesn't receive the ActionEvent. I am trying to hide the popup menu associated with the JMenu when there is invalid text in a certain text field, because I want the user to fix the text field before moving on.
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Perhaps you need to call repaint() to force your Frame to draw itself again?
 
Nathan Pruett
Bartender
Posts: 4121
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sounds like you should put a listener on the field you are concerned with and toggle setEnabled() on the JMenu. Then the menu would grey out and the user couldn't click on it when there was not valid data in the textfield, and when there was valid data there, the menu would show and behave normally.

-Nate
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic