I have a class
public class Speciality {
String specName;
String eduProgram; }
and a TreeMap Map<String, ArrayList<Speciality>> treeMap = new TreeMap<String, ArrayList<Speciality>>();
where String is the name of faculty.
My 1st JComboBox comprises of names of faculties (so they're equal to keys in my Map) and in my BoxActionListener
I need to fill my 2nd JComboBox with the array of specNames
.
Here you can see what I actually need, but ofc it doesn't word (because I cast String[] to String)
boxSpeciality.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for(int i = 0; i < treeMap.size(); i++){
Object key = treeMap.keySet().toArray(new Object[treeMap.size()])[i];
ArrayList<Speciality> value = treeMap.get(key);
if(key == boxFaculty.getSelectedItem()){
boxSpeciality.setModel(new DefaultComboBoxModel((String[]) value.get(i).specName));
}
}
}
});
As I understand, your combobox boxFaculty
shows the keys of treeMap
which are faculty names and your combobox boxSpeciality
should show the specialities of each faculty ( which is one of the values of the treeMap
).
If you want the boxSpeciality
to be populated based on selection of boxFaculty
, you should write an actionListener
on boxFaculty
.
Another thing to note is do not set a new DefaultComboboxModel
everytime in the action listener. Set one when you defined the combobox and update its elements in the action listener.
You can do something like below:
DefaultComboBoxModel<Speciality> specialityModel = new DefaultComboBoxModel<Speciality>();
boxSpeciality.setModel( specialityModel );
boxFaculty.addActionListener( new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
Object obj = boxFaculty.getSelectedItem();
if ( obj != null )
{
ArrayList<Speciality> specialities = treeMap.get( obj );
specialityModel.removeAllElements();
for ( Speciality speciality : specialities )
{
specialityModel.addElement( speciality );
}
}
}
});
This will update the boxSpeciality
box everytime you select an item in boxFaculty
.