Question

Ok, so I have a JList with several items. I select an item, and click a button. When I click the button, I want the background color of that item changed permanently.

I already created a custom renderer, but all I can do with it change the color of the entire background or change the color of the background of selected item while it is selected. That's not what I want. I tried to obtain the Rectangle object using getBounds (so I could do something like paint everything inside the area of the Rectangle?) but I don't even know how to start.

I figured by now that JList's CellRenderer doesn't support this kind of stuff, so I think I have to do something like creating a serie of readOnly textFields, set its styles individually, and somehow show them as a list?

I don't really need any code (unless you want to give an example), I'm just looking for a general direction of how I would do this.

Sorry for the long text. Thanks!

Was it helpful?

Solution

You do the same thing you are doing, but write out your code logic to lock in the rendered color if the user's actions indicate that it should be locked. The key is in your code logic. Perhaps you want to change the state of the object that is being rendered, or perhaps you want to change the state of a Map that holds the rendered colors as values and the displayed objects as keys. I'd probably go with the latter.

e.g.,

// ListItemType is whatever type is being displayed in your JList.
Map<ListItemType, Color> listItemBackground = new HashMap<ListItemType, Color>();
// now add each item to the JList with the default background color.
  • Your renderer will use this Map to decide which background color to paint.
  • When the user makes his selection and makes the item have a new background color, you change the color held by the Map and repaint the list.
  • Make sure that you make the renderer not opaque if its to show its background.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top