Search code examples
javaswingobjectjcombobox

get value from object and add in jcombobox


nice day for you i have jcombobox a fill it from database by object and it work fine with this code :

final JComboBox pruCompanyCB = new JComboBox(DAOFactory.getInstance()
                            .getPruComanyDAOImpl().findAll().toArray());
pruCompanyCB.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        JComboBox comboBox = (JComboBox) arg0.getSource();
        PruCompany pruCompany = (PruCompany) comboBox.getSelectedItem();
        CRSevice.getInstance().getPruCompanySrv().setPruCompany(pruCompany);

and use next code to get selected

car.setPruCompany((PruCompany) pruCompanyCB.getSelectedItem());

But in gui the items in combobox appear like

PruCompany{id=1, country= Country{id=4, name="USA"}}

like object toString() format

how getName() from pruCompany object and show just name in combobox without change toString() method in model class any way please best regards and wishes


Solution

  • The other approach is to create a custom renderer to display a specific property from the Object added to the ComboBoxModel.

    Combo Box With Custom Render gives an example of how to create a custom renderer.

    Most people when creating a custom renderer forget to implement a custom KeySelectionManager so that selection of items can also be done with the keyboard and not just the mouse. The renderer used in the above link with also support this functionality.