I'm working on a project where I need to be able to choose colors from a JComboBox. The catch is some of the colors have stripes. I've looked at a few tutorials and none seem to help. What I currently have is a JPanel as the component to be drawn in the list. Here's the code:
When I run the program, it just shows the return from the toString() method in each slot of the list. Please help me.
Life is 10% what happens and 90% how you react to it.
Attitude is everything.
Originally posted by Derek Boring: When I run the program, it just shows the return from the toString() method in each slot of the list.
I'm having to guess here, since you don't show the code where you populate the JComboBox and set its renderer, but it seems that perhaps you are putting instances of your ListCellRenderer in your combo box. Though that's not strictly impossible to do, it's certainly not the way it's supposed to work.
The way it's supposed to work is that you put values (which may be of any class you like) in your combo box, and the combo box has a single renderer which is responsible for drawing the visual representation for each of the various values.
See how your implementation of this method ignores the value parameter? That's no good, because it means that every object in a JComboBox or JList using your renderer will be drawn exactly the same way. This method should return a Component that has been configured correctly for the specific value passed in. [Also, getWidth() and getHeight() are no good here because renderers aren't added to Containers in the same way that regular Components are, and this would be too soon anyway. repaint() is similarly useless.]
Based on your code, I can think of two obvious ways to do things correctly:
1) Have a class called ColorStrip which has no painting code, just fields such as mainColor and horizStripeColor. Have another class called ColorStripRenderer which implements ListCellRenderer and knows how to draw any ColorStrip. Populate your combo box with instances of ColorStip and set its renderer to a ColorStripRenderer.
2) Populate your combo box with java.lang.Integers, and set a renderer which adjusts its colors based on the value of the Integer it sees.
I think #1 might be a better approach, but I'll go with #2 here because it requires fewer changes to your existing code.
[edit: tweak border, misc typos] [ November 14, 2007: Message edited by: Brian Cole ]