本文介绍了自定义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部分有效,但是我不知道为什么它不会改变单元格的背景颜色.任何人都有任何想法,谢谢!

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!

推荐答案

主要问题是标签默认情况下是不透明的,因此您需要使标签不透明才能绘制背景.

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:

list.setSelectionBackground(Color.RED);

如果您要创建一个渲染器以使文本右对齐,则可以在默认渲染器上设置一个属性:

If you are trying to create a renderer to right align the text then you can just set a property on the default renderer:

DefaultListCellRenderer renderer = (DefaultListCellRenderer)list.getCellRenderer();
renderer.setHorizontalAlignment(SwingConstants.RIGHT);

这篇关于自定义ListCellRenderer不会更改背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 10:41