• Post Reply Bookmark Topic Watch Topic
  • New Topic

How do I accomplish this?

 
ernest fakudze
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
My UI has a JComboBox and a JButton next to it. The JCBx has 4 items for dropping down and the first item is the default (nothing selected and it is a string of length 0). Now the JBtn is disabled when the UI initially fires up. I want this btn to be enabled as soon as a valid option is selected from the JCBBx. So far I'm trying to make my UI an ItemListener (implements ItemListener). I then try to enable the button in the itemStateChnage() method but it isn't working. How should I do this? Code snippet below:
public void itemStateChanged(java.awt.event.ItemEvent itemEvent) {
String s;

if( itemEvent != null ) {
s = (String) itemEvent.getSource();
if( s.equals("selection") ) {
if( !acceptBtn.isEnabled() ) {
acceptBtn.setEnabled( true );
}
}

}
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24213
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The getSource() method will return a reference to the JComboBox, so it won't ever be equal to the string "selection". Anyway, if you get an event, it will be because the selection has changed, and unless you're planning on testing by passing "null" as an argument, an event parameter will never be null. Finally, in Java, you can and should declare variables at their first use, not at the top of a block, as in C. So I'd write the handler like this:

This handler will get called twice each time the user makes a selection -- once when the old item is deselected, and again when the new one is selected. You could use an ActionListener instead, which will only be invoked once when the selection is completed.
 
ernest fakudze
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ernie. Now it's working.
RE: in Java, you can and should declare variables at their first use, not at the top of a block, as in C
>>> Thanks, I am already aware of this. I wrote the code the way I did because I was doing a quick test.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!