问题
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