Reputation:
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
Upvotes: 0
Views: 610
Reputation: 324098
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.
Upvotes: 1
Reputation: 559
Your problem comes from the fact that JComboBox uses the toString() method of its members to create the GUI Text output.
So you have to overwrite the toString() method in the PruCompany class if you want to change this behaviour fast.
If you have more time or the toString() method of PruCompany is really important, you can implement a helper class and overwrite its toString() method.
The label attribute of this ComboItem will be displayed on the GUI, but you have to create the JComboBox with an Array of ComboItem objects to achieve that effect.
For more information, look there.
public class ComboItem {
private String value;
private String label;
public ComboItem(String value, String label) {
this.value = value;
this.label = label;
}
public String getValue() {
return this.value;
}
public String getLabel() {
return this.label;
}
@Override
public String toString() {
return label;
}
}
Upvotes: 1