ListCellRenderer,选中的值不可见

时间:2016-12-02 13:28:03

标签: java jcombobox listcellrenderer

我有JComboBox,我按照以下方式应用ListCellRenderer:

    colorList = new JComboBox<>(COLORS_NAMES);
    ColorComboBoxRenderer renderer = new ColorComboBoxRenderer(colorList);
    renderer.setColors(COLORS);
    renderer.setColorNames(COLORS_NAMES);
    colorList.setRenderer(renderer);

它导致了单元格的细节,但我找不到为什么选择的值会被记住而不是图片的原因。如下:

enter image description here

这是我的渲染器代码(省略setColors,getColors等..)

class ColorComboBoxRenderer extends JPanel implements ListCellRenderer{

    JPanel textPanel;
    JLabel text;

    public ColorComboBoxRenderer(JComboBox combo){
        textPanel = new JPanel();
        textPanel.add(this);
        text = new JLabel();
        text.setOpaque(true);
        text.setFont(combo.getFont());
        textPanel.add(text);
    }

    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
            boolean cellHasFocus) {
        if (isSelected){
            list.setSelectionBackground(colors[list.getSelectedIndex()]);
        }
        else{}

        if(colors.length != colorNames.length){
            System.out.println("colors.length doesn't match colorNames.length");
            return this;
        }
        else if(colors == null){
            System.out.println("Set colors by setColors first.");
            return this;
        }
        else if(colorNames == null){
            System.out.println("Set colorNames by setColorNames first.");
            return this;
        }

        text.setText(" ");

        if(index > -1){
            text.setBackground(colors[index]);
            text.setText(" ");
        }

        return text;
    }
}

让我感到困惑的是,每当我将光标指向指定的单元格时,if(isSelected) block就会完成,但我的直觉宁愿期望在cellHasFocus param为真时发生。

提前致谢,因为我在2天后一直在努力; /

编辑1

将JComboBox字段添加到ColorComboBoxRenderer类,并在构造函数中初始化它:

private JComboBox comboBox;
public ColorComboBoxRenderer(JComboBox combo) {
        this.comboBox = combo;
        //rest of code as it was 
    }

改变了:

    if(isSelected){
        list.setSelectionBackground(colors[list.getSelectedIndex()]);
    }

要:

    if (isSelected){
        list.setSelectionBackground(colors[list.getSelectedIndex()]);
        comboBox.setBackground(colors[list.getSelectedIndex()]);
    }

结果:

enter image description here

现在效果更好,所以也许您知道如何更改JComboBox背景但不影响下拉箭头?

1 个答案:

答案 0 :(得分:0)

在编辑1中,重要的是我们编辑了ComboBox,这是必要的,因为ListRenderer只生成dropDown列表及其单元格,但不会影响ComboBox字段。所以必要的,我终于找到了它,是相当蛮力的方法。我在编辑1中选择后更改了整个ComboBox背景,但随后返回了Arrow State,它位于JComboBox的Index(0)。最后这部分代码应该是这样的:

       if (isSelected){
            list.setSelectionBackground(colors[list.getSelectedIndex()]);
            comboBox.setBackground(colors[list.getSelectedIndex()]);
            comboBox.getComponent(0).setBackground(new JButton().getBackground());
        }

现在一切都按设计工作:

enter image description here