Java – find features in a jComboBox that are found in the .NET ComboBox

cjavajcombobox

I am .net C# programmer that wants to learn Java. I can connect DB, getting and writing data with JDBC. But how can I fill JComboBox and set its DisplayMember "PersonelName" and ValueMember "PersonelID"?

In .NET there is related properties like DisplayMember, DataSource, ValueMember, I can show personel's name with displaymember and when I am writing to data I can learn personnel's id from valuemember property. But in Java there is no properties like this. How can I get PersonelID and show Personel Name in JCombobox in Java?

Would someone give me an example?

Best Answer

JComboBox constructor can take a ComboBoxModel as argument. DefaultComboBoxModel is a concrete implementation of the ComboBoxModel interface.

So, if you have a Personel class:

class Personel{
    String personelName;
    int personelId;
    //getters, setters

    //This will be your display member
    @Override
    public String toString(){
        return this.personelName;
    }
}

And supposing you obtained all personel via JDBC and have it stored in a new Vector, you can do:

DefaultComboBoxModel comboModel = new DefaultComboBoxModel(personel);
JComboBox myCombo = new JComboBox(comboModel);

At runtime, you can getModel and setModel to access the JComboBox model. The display member will be Personel's toString() method. The value member will be the actual object stored in the DefaultComboBoxModel vector, in this case a Personel instance.

I suggest you take a look at the API documentation for ComboBoxModel and DefaultComboBoxModel.