【发布时间】:2016-12-02 13:28:02
【问题描述】:
我有 JComboBox,我在其中应用 ListCellRenderer,如下所示:
colorList = new JComboBox<>(COLORS_NAMES);
ColorComboBoxRenderer renderer = new ColorComboBoxRenderer(colorList);
renderer.setColors(COLORS);
renderer.setColorNames(COLORS_NAMES);
colorList.setRenderer(renderer);
它导致修改单元格,但我找不到选择值被记住但没有被描绘出来的原因。如下:
这是我的渲染器代码(省略 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 参数为真时会发生这种情况。
提前感谢,因为我从 2 天开始就一直在努力解决这个问题;/
编辑 1
在 ColorComboBoxRenderer 类中添加 JComboBox 字段,并在构造函数中对其进行初始化:
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()]);
}
结果:
现在效果更好了,也许你知道如何改变 JComboBox 背景但不影响下拉箭头?
【问题讨论】:
标签: java jcombobox listcellrenderer