I have a difficult problem with this code:
public class StatusAndPersonPanel implements ActionListener {
private JPanel myPanel;
private String[] status = {"Good", "Bad", "Not so bad"};
private Color[] backgrounds = {Color.GREEN, Color.RED, Color.ORANGE};
private JComboBox<String> box;
public ComboboxConstructor() {
myPanel = new JPanel();
box = new JComboBox<String>(status);
ComboBoxRenderer myBackgrounds = new ComboBoxRenderer(box);
myBackgrounds.setColors(backgrounds);
myBackgrounds.setStrings(status);
box.setRenderer(myBackgrounds);
box.addActionListener(this);
Color selectedColor = (Color) backgrounds[box.getSelectedIndex()];
box.setBackground(selectedColor);
myPanel.add(box); // putting it into my panel
}
@Override
public void actionPerformed(ActionEvent event) {
Color selectedColor = (Color) backgrounds[box.getSelectedIndex()];
box.setBackground(selectedColor);
}
}
As you can see in the image, in Step 1 all colors are made as I want them,
but now I click on "not as bad" and the JComboBox
collapses with the right choice, but doesn´t change the color (the arrow does, I don´t know why), until my focus is lost (Step 3, clicking another `JPanel element) the color is given properly.
Now, I know it´s just a little cosmetic problem, but it´s driving me crazy! I tried it with ActionListener
, ItemListener
(after change), and FocusListener
(focus lost and gained), but the result stays always the same as shown in Step 2.
Thank you so much for your help and thoughts in advance!
A JComboBox
is displayed using a single renderer for all cells. You can change the color in your ListCellRenderer
, as shown in the CustomComboBoxDemo
.
Addendum: Related examples may be found in this Q&A.