本文介绍了Java List set 列表项的背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何更改 Java AWT 列表项的背景颜色?我的意思是 AWT 列表中的单个项目,而不是整个项目.
How does one change the background color of a Java AWT List item? By that I mean a single item in a AWT List, not the whole thing.
推荐答案
您需要一个自定义渲染器.也就是说,如果您使用的是 Swing.最好坚持使用 Swing 组件而不是 awt gui 组件.
You'll need a custom renderer. That is, if you're using Swing. It's better to stick with the Swing components and not the awt gui components.
JList
...
setCellRenderer(new MyCellRenderer());
...
class MyCellRenderer extends DefaultListCellRenderer
{
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
{
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
Color bg = <calculated color based on value>;
setBackground(bg);
setOpaque(true); // otherwise, it's transparent
return this; // DefaultListCellRenderer derived from JLabel, DefaultListCellRenderer.getListCellRendererComponent returns this as well.
}
}
这篇关于Java List set 列表项的背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!