Java列表设置列表项的背景 [英] Java List set Background of list item

查看:168
本文介绍了Java列表设置列表项的背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

怎样才能改变一个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列表设置列表项的背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆