Java ComboBox of varying value for a name

I have a Java combo box and a project related to a SQLite database. If I have an object with an associated ID and name:

class Employee { public String name; public int id; } 

what's the best way to put these entries in a JComboBox so that the user sees the name of the employee, but I can restore the employeeID when I do this:

 selEmployee.getSelectedItem(); 

thanks

+6
source share
4 answers

First method: we implement toString() in the Employee class and force it to return a name. Make your model with a list of Employee instances. Upon receiving the selected object from the combo, you will receive an instance of Employee, and you can get its identifier.

The second method: if toString() returns something other than the name (for example, debugging information), do the same as above, but additionally set your own cell rendering in your combo. This cell handler will need to assign the value Employee and set the label text to the employee name.

 public class EmployeeRenderer extends DefaulListCellRenderer { @Override public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); setText(((Employee) value).getName()); return this; } } 
+10
source

Add the employee object to the JComboBox and overwrite the toString method of the employee class to return the name Employee.

 Employee emp=new Employee("Name Goes here"); comboBox.addItem(emp); comboBox.getSelectedItem().getID(); ... public Employee() { private String name; private int id; public Employee(String name){ this.name=name; } public int getID(){ return id; } public String toString(){ return name; } } 
+6
source

I think the best and easiest way to do this would be to use a HashMap something similar when you populate your JComboBox with a ResultSet

 HashMap<Integer, Integer> IDHolder= new HashMap<>(); int a=0; while(rs.next()) { comboBox.addItem(rs.getString(2)); //Name Column Value IDHolder.put(a, rs.getInt(1)); //ID Column Value a++; } 

Now, when you want to get the identifier of any selected comboBox list item, you can do it simply

 int Id = IDHolder.get(comboBox.getSelectedIndex()); 
+3
source

You can create your own DefaultComboBoxModel . In this, create a vector of your data in your case Vector<Employee> empVec . You need to further override the getSelectedItem() method and use getSelectedIndex() to extract the value from the vector.

0
source

Source: https://habr.com/ru/post/914564/


All Articles