Why we use Combo Boxes
Combo boxes are a drop down menu option for forms. They allow us to limit the number of potential choices for a person to make, increasing the chance of a person picking a valid and correct option.
In our example where we were extending a class for a Java GUI, we were building a student record. If that record were to hold a college major you could potentially have all types of incorrect answers. Consider the major of Computer Science, you might have people entering CS, Comp. Sci., Computer Science, in addition to misspelling it. Someone might enter a major that the school doesn’t even offer.
By limiting the options, you get more control, and fewer mistakes.
So lets update our class, to support the JComboBox.
Adding the JComboBox
The first thing we’re going to do convert our JTextField
into a JComboBox
.
In our Class variable section, find the major field, and convert it to a JComboBox
.
// JTextField major;
JComboBox major;
Next, in the constructor we’re going to need to convert the JTextField
into a JComboBox
as well.
// major = new JTextField();
major = new JComboBox( );
However, this will generate an error because the JComboBox
will want a list of items. You can pass in an array of objects, like Strings, or a Vector of Elements. I chose an array of objects.
String majors[] = {"Art", "Business", "Computer Science", "History"};
major = new JComboBox( majors );
This will be the list which we use. If you want new majors, you’ll need to add them to the array majors.
In the displayStudent()
method, comment out the major.setText(student.getMajor)
. We’ll update that in a minute.
Selecting a Default Value in the JComboBox
By default, the JComboBox
will select the first element. If you want to set a different value, like when you read from a student, you will need to update the JComboBox
.
Luckily there are various methods we can use. The easiest is setSelectedItem()
. You pass in a value, and if it can match it, it will set that value for you.
this.major.setSelectedItem(student.major);
Remember, this is wrapped in an if statement, to make sure student is not null already.
Getting the setSelectedItem()
is a little slower that setSelectedIndex()
, so if you know the index, use it. If not, feel free to use the setSelectedItem().
Reading a Value from a JComboBox
Reading a value from a JComboBox
isn’t too difficult. Just like there is a setSelectedItem()
method, there is a getSelectedItem()
method. However, this returns an Object, so you might need to use a toString()
method to get the result you need, especially if it is not a String object.
String majorValue = this.major.getSelectedItem().toString();
Combo Boxes in Java Swing was originally found on Access 2 Learn
One Comment
Comments are closed.