【发布时间】:2011-03-17 05:58:45
【问题描述】:
如何更改 Java AWT 列表项的背景颜色?我的意思是 AWT 列表中的单个项目,而不是整个项目。
【问题讨论】:
-
触动,但我已经看过了,我是一个试图跳过建筑物的矮个子的无助:(
-
你要学会不要这么“无助”。要么这样,要么你需要远离软件开发。
-
好吧,我退出了。我现在要一辈子洗碗了。 :)
如何更改 Java AWT 列表项的背景颜色?我的意思是 AWT 列表中的单个项目,而不是整个项目。
【问题讨论】:
您需要一个自定义渲染器。也就是说,如果您使用的是 Swing。最好坚持使用 Swing 组件而不是 awt gui 组件。
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 AWT List继承自Component,所以使用Component的setBackground(Color c)方法。
List coloredList = new List(4, false);
Color c = new Color(Color.green);
coloredList.add("Hello World")
coloredList.setBackground(c);
列表现在具有绿色。
【讨论】:
我使用 AWT 已经有一段时间了,但你不能只使用 setBackground(Color) 吗? List 是 java.awt.Component 的子类。
【讨论】: