自定义ListCellRenderer不会改变背景颜色
我有这样的课程:
@SuppressWarnings("serial")
private class DataCellRenderer extends JLabel implements ListCellRenderer
{
public DataCellRenderer()
{
setHorizontalAlignment(SwingConstants.RIGHT);
}
@Override
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus)
{
if(isSelected)
setBackground(Color.red);
setText(" " + value.toString());
return this;
}
}
问题是当我在 JList 中选择一个单元格时,我的背景不会变成红色。 setText 部分有效,但我不明白为什么它不会改变单元格的背景颜色。大家有什么想法吗,谢谢!
I have this class:
@SuppressWarnings("serial")
private class DataCellRenderer extends JLabel implements ListCellRenderer
{
public DataCellRenderer()
{
setHorizontalAlignment(SwingConstants.RIGHT);
}
@Override
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus)
{
if(isSelected)
setBackground(Color.red);
setText(" " + value.toString());
return this;
}
}
The problem is that my Background will not turn red when I select a cell in my JList. The setText part works but I can't figure out why it will not change my background color of the cell. Anyone have any ideas, Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
主要问题是标签默认是不透明的,因此您需要使标签不透明才能绘制背景。
但您不需要为此创建自定义渲染器。默认渲染器是不透明的。您需要做的就是设置列表的选择背景属性:
如果您尝试创建一个渲染器来右对齐文本,那么您只需在默认渲染器上设置一个属性:
The main problem is that labels are non-opaque by default, so you need to make the label opaque in order for the background to be painted.
But you don't need to create a custom renderer for this. The default renderer is opaque. All you need to do is set the selection background property of the list:
If you are trying to create a renderer to right align the text then you can just set a property on the default renderer:
例如
for example
默认情况下,
JLabel
是透明的。如果你想让它显示背景,你需要:另外,你经常想要使用父列表的默认背景颜色,这将适合 UI 主题或列表本身的自定义:
将它们放在一起:
By default
JLabel
is transparent. If you want it to show a background, you need:Also, you often want to use the default background colour of the parent list, which will fit with the UI theme or customisation of the list itself:
Putting it all together: