I have a major issue with a JComboBox object. I have a class that extends JComboBox and in it I register a ListCellRenderer via
the setRenderer method. This JComboBox contains an array of GradeData objects lets just call them grade1 - 6. My ListCellRenderer
looks like this
So far so good. It displays the grade values to the JLabel objects in the renderer but it messes around with my blank value.
It displays a sequence of my list values at the top of the popup menu instead of a empty blank value? How do i keep the blank
value from not being rendered by the ListCellRenderer. I know i am missing something really obvious here but can't tell what.
Shouldn't be the cause of your problem, but don't extend JComboBox. You only extend a class to add new functionality. Adding data or setting properties is not adding new functionality.
A renderer is shared by all items. I don't see where you ever set the text of the label when you add a String to the combo box. Not sure if this causes the problem or not.
I would suggest you extend BasicComboBox as it will set all the properties of the renderer and then simply invoke toString() on any object you add to the combo box to get the text to display. Then you can check if a Grade object has been added and reset the text.
So the basic logic might be something like:
Also, note that when you use a custom renderer you will break the functionality of the combo box since selection of an item from the combo box using the keyboard will not work. In this case it will not be a big issue since all your items start with the same string.
Note: you could just simply implement the toString() method of your Grade class to return the grade and then you don't need a custom renderer. Although many people will say you should use the toString() method as data for your application.
Thank you so much for your very kind and enlightening answer. I have solved this issue now thank to your help. Now the blank string value shows up the way
wanted it to. This is how my renderer looks like now
Respectfully and in appreciation kind regards,
posted 3 months ago
Why do you have all that extra code? Did you try what I posted?
The point of invoking super.getListCellRenderer(..) is that it will set all the defaults of the renderer.
You then have a simple if condition to override the text in your special case.