0

I have a JComboBox of type myclass. I use CustomListRender to display one of the attributes of myclass, and it works fine.

Then I set myCombobox.setEditable(true). JComboBox becomes editable, but by default text is set to somthing like this in combobox:

 com.mypackagename.myclass

Can anyone tell me how to solve this problem?

Thanks in advance.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
Krishna Shrestha
  • 1,662
  • 14
  • 38

1 Answers1

2

As discussed in How to Use Combo Boxes: Providing a Custom Renderer,

The default renderer knows how to render strings and icons. If you put other objects in a combo box, the default renderer calls the toString method to provide a string to display.

Unless overridden, you're probably seeing the toString() implementation inherited from Object. At a minimum, you'll need to override MyClass#toString() or update your renderer supply a custom editor accordingly; there's a related example here. Most would prefer the latter; your sscce showing your custom renderer would make it easier to suggest alternatives.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • `MyClass` used to conform to Java class naming convention. – trashgod Oct 07 '12 at 16:21
  • As far as I understand the question, he already has a custom renderer. What he needs is a custom editor as well, to avoid the `toString` call of the standard editor. And I am not a big fan of overriding the `toString` for UI purposes – Robin Oct 07 '12 at 16:32
  • @Robin: Good point about the editor; updated. I'd welcome a more relevant example than the one I cited. I'm more sanguine about overriding `toString()`, say in `enum`. I focused on that to explain the (presumed) result mentioned in the question. Can you elaborate on the pitfalls? – trashgod Oct 07 '12 at 16:48
  • Not a real pitfall, except that even in production code I dare changing the `toString` method regularly to provide better information (for example for printing more information in a logger). A hidden dependency on that method by using a default renderer/editor iso a custom one could break a UI in that case. And my IDE would never discover that the `toString` was used in the renderer – Robin Oct 07 '12 at 18:45