如果房间处于紧急模式,那么我想在列表框中将其显示为红色。 “我的列表”框使用“列表模型”显示其所有项目。 GUI displaying the rooms 无论如何循环遍历列表框中的每个元素以更改其文本的颜色?
答案 0 :(得分:0)
添加自定义单元格渲染器。以下示例来自here:
public class MyCellRenderer extends JLabel implements ListCellRenderer<Object> {
final static ImageIcon longIcon = new ImageIcon("long.gif");
final static ImageIcon shortIcon = new ImageIcon("short.gif");
// This is the only method defined by ListCellRenderer.
// We just reconfigure the JLabel each time we're called.
public Component getListCellRendererComponent(
JList<?> list, // the list
Object value, // value to display
int index, // cell index
boolean isSelected, // is the cell selected
boolean cellHasFocus) // does the cell have focus
{
String s = value.toString();
setText(s);
if (room.getMode() == RoomConstants.EMERGENCY_MODE) {
setForeground(Color.RED);
}
setEnabled(list.isEnabled());
setFont(list.getFont());
setOpaque(true);
return this;
}
}
myList.setCellRenderer(new MyCellRenderer());
希望有所帮助。