Add an object to a JComboBox but show a string without overriding the object's .toString() method

感情迁移 提交于 2019-12-11 12:12:07

问题


The object class that I am working with already has its .toString() method overridden, giving its name. But I am using same object in a JComboBox and I need to display another String. Is there a way to accomplish this?


回答1:


You bet there is! What you want to do is to give your JComboBox a custom cell renderer.

To do this, you could extending DefaultListCellRenderer making sure to override its getListCellRendererComponent(...) method. Once you've done this, you would call setRenderer(...) on your JComboBox, passing in an object of your new class.

For more on this, please be sure to check out the renderer section of the JComboBox tutorial.




回答2:


Check out Combo Box With Custom Renderer.

If you just use a custom renderer you will break the default functionality of the combo box that allows the user to select an item using the keyboard. The user should be able to use the mouse or keyboard when using a GUI.

The above solution shows how to implement the KeySelectionManager so you retain this default functionality.



来源:https://stackoverflow.com/questions/25432381/add-an-object-to-a-jcombobox-but-show-a-string-without-overriding-the-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!