Java Combo Boxes
You will also have a new form on which to add controls.
The JComboBox
Control
A combo box is a
drop down list of items that can be selected by a user. It can be found in the
NetBeans palette, under Swing Controls:Click back onto your Combo Box to highlight it. Right-click and select Change Variable Name from the menu that appears. Type comboOne as the new name, and then click OK.
Change the name of the button in the same way, rename it btnComboBox. Change the text on the button to Get Drop Down Item.
Change the name of the Text Field to txtComboBoxItem. Delete the default text and leave it blank. Your form should then look something like this one:
Click back onto your Combo Box to select it. Now look at the properties window on the right of NetBeans. Locate the model property:
Run your programme and test it out: (Just click OK when it asks you to choose the Main Class.)
When the button is clicked, we want the item chosen to appear in the text field. So double-click your button to create a code stub.
To get which item is selected there is a handy method of combo boxes called getSelectedItem. But this returns an Object as a value. What we want is the text from the list. You can do something called casting to turn the Object into a String. Add the following line to your code stub:
String itemText = (String)comboOne.getSelectedItem( );
So we're setting up a string variable called itemText. After the equals sign we use the getSelectedItem method of comboOne. But note how the casting is done - with the String variable type between round brackets. This goes immediately before the object or value you're trying to cast (casting just means converting from one variable type to another).
To display the selected item in the text field, you just need to set the text for the text field. Add this line just below the line you have:
txtComboBoxItem.setText( itemText );
Run your programme again and try it out. Select an item from your drop down list. Then click your button. The item you selected should appear in the text field:
Comments
Post a Comment