Je JComboBox où je demande ListCellRenderer comme suit:ListCellRenderer, valeur sélectionnée non visible
colorList = new JComboBox<>(COLORS_NAMES);
ColorComboBoxRenderer renderer = new ColorComboBoxRenderer(colorList);
renderer.setColors(COLORS);
renderer.setColorNames(COLORS_NAMES);
colorList.setRenderer(renderer);
il a un résultat dans les cellules acteur de modification, mais je ne peux pas trouver des raisons pour lesquelles la valeur sélectionnée se souvient mais pas représenté. Comme suit:
Voici mon code pour renderer (en omettant setColors, getColors etc ..)
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;
}
}
Ce qui me embrouille est aussi que if(isSelected) block
est fait chaque fois que je signale le curseur sur la cellule spécifiée , mais mon intuition s'attendrait plutôt à ce que ça arrive quand cellHasFocus
param est vrai.
Merci à l'avance, comme je me bats avec elle depuis 2 jours;/
EDIT 1
Ajouté champ JComboBox à la classe ColorComboBoxRenderer, et il initialise dans le constructeur:
private JComboBox comboBox;
public ColorComboBoxRenderer(JComboBox combo) {
this.comboBox = combo;
//rest of code as it was
}
Changé cela:
if(isSelected){
list.setSelectionBackground(colors[list.getSelectedIndex()]);
}
À:
if (isSelected){
list.setSelectionBackground(colors[list.getSelectedIndex()]);
comboBox.setBackground(colors[list.getSelectedIndex()]);
}
Résultats dans:
Maintenant, l'effet est mieux, alors peut-être u ont une idée comment changer de fond JComboBox mais n'affectent pas la flèche déroulante?