Quick JComboBox Event Question
Hi! I'm working on a program that displays a list of formulas in a combo box where the user will select one, and then two text boxes will show up where they enter the variables and submit for the solution. It's a pretty basic concept and I could do it no problem in VB/C#/C++ but I can't seem to find the Java syntax for it.. :confused:
Here's my code from the section where the condition needs to be:
Code :
box.addItemListener(
new ItemListener(){
public void itemStateChanged(ItemEvent event)
{
add(button);
Select Case(box.selectedIndex)
Case 1:
add(text1);
add(text2);
Case 2:
add(text3);
add(text4);
etc.
}
}
);
I'm pretty sure that's not the correct syntax for the case statement either but that's the basic idea of what I'm trying to do. Thanks for any help!
Re: Quick JComboBox Event Question
see The switch Statement (The Java™ Tutorials > Learning the Java Language > Language Basics)
I made a few changes to the code below
Code :
box.addItemListener(
new ItemListener(){
public void itemStateChanged(ItemEvent event)
{
if ( event.getStateChange() != ItemEvent.SELECTED ){return;}//if this is NOT a selection event
add(button);
switch (box.getSelectedIndex())://get the selected index of the JComboBox
case 1:
add(text1);
add(text2);
break;
case 2:
add(text3);
add(text4);
break;
etc.
}
}
);
Note that if you are adding actual Swing components to your GUI, you need to call revalidate() on the container to which you are adding them
Re: Quick JComboBox Event Question
Alright, that's a good bit closer. However, none of the cases execute until after I change the selection a second time. Then it will display perfectly while switching between the first and second selections, but will display an extra set of labels and boxes after switching down to the third selection and back up to the others.
Also the revalidate function wasn't being recognized for some reason unless there's an import I missed but I put in the invalidate, validate statements which is evidently what the revalidate does.
Sorry for the noob questions but I appreciate the help. :)