I need to implement color choices using JComboBox. Wrote this renderer:

private class ColorCellRenderer implements ListCellRenderer { protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer(); public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { JLabel renderer = (JLabel) defaultRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value instanceof Color) { renderer.setBackground((Color) value); renderer.setText(" "); } return renderer; } } 

The problem is that when you select an item from the JComboBox list, the background color changes for the entire JComboBox (including the button), and not just for its text field.

  • if you have already tried all the setters and nothing happened then you can check if there is any possibility to change it: change the look & feel. if the color changes: change the look & feel settings / write your own anyway: inherit from JComboBox and reload the method that draws the component - jmu
  • Many thanks, I decided to try to write my look & feel. - alnasfire
  • Found an interesting link: bugs.sun.com/bugdatabase/view_bug.do?bug_id=4337049 - alnasfire
  • Found a way not to use LaF. You need to write your editor and screw this ActionListener: jComboBox.addActionListener (new ActionListener () {@Override public void actionPerformed (ActionEvent e) {jComboBox.getComponents () [0] .setBackground (new JComboBox (). GetBackents () [0] .setBackground (new JComboBox (). GetBackents () [0] .setBackground (new JComboBox (). GetBackents () [0] .setBackground (new JComboBox (). GetBackents () [0] .setBackground (new JComboBox (). GetBackents () [0] .setBackground (new JComboBox (). GetBackents () [0] .setBackground (new JComboBox ()) getBack }); - alnasfire

1 answer 1

and one more more elegant solution, in which it is enough to add one line of code to the renderer and forget about writing your editor:

list.setSelectionBackground ((Color) value);