简体   繁体   English

在Java中创建JList,如何更改条目的背景颜色?

[英]Creating a JList in Java, how would I change the background color of a entry?

Ok, so I have a JList with several items. 好的,所以我有一个包含几个项目的JList 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. 我试图使用getBounds获取Rectangle对象(所以我可以做一些像在Rectangle区域内绘制所有内容的东西?)但我甚至不知道如何开始。

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? 我现在觉得JListCellRenderer不支持这种东西,所以我想我必须做一些事情,比如创建一个readOnly textFields系列,单独设置它的样式,并以某种方式将它们显示为列表?

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! 谢谢!

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. 也许您想要更改正在渲染的对象的状态,或者您可能希望更改将渲染颜色保存为值并将显示的对象保存为键的Map的状态。 I'd probably go with the latter. 我可能会选择后者。

eg, 例如,

// 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. 您的渲染器将使用此Map来决定要绘制的背景颜色。
  • 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. 如果要显示其背景,请确保使渲染器不是不透明的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM