When running the code below, all parts of the JComboBox are colored when setEditor = true; However when setEditor = false, only the drop-down list can be colored.
It seems the entry field looks like "disabled" without any way to change its color. I tried to issue a setEnabled() for this part, but with no success. I have also tried many other things for months but all failed.
Is there a solution?
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.Color;
import java.awt.Component;
import javax.swing.ComboBoxEditor;
import javax.swing.DefaultListCellRenderer;
public class CustomComboBox
{
public static void main(String[] args)
{
String[] items = { "Apples", "Bananas", "Cherries", "Oranges" };
JFrame frame = new JFrame("JComboBox Custom Colors");
frame.setSize(213, 200);
frame.getContentPane().setLayout(null);
JButton Finish = new JButton("Exit");
Finish.addActionListener(e -> System.exit(0));
Finish.setBounds(43, 133, 100, 23);
JComboBox<String> comboBox = new JComboBox<String>(items);
comboBox.setBounds(43, 23, 101, 20);
comboBox.setRenderer(new DefaultListCellRenderer()
{
private static final long serialVersionUID = 1L;
@Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected,
boolean cellHasFocus)
{
Component renderer = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
renderer.setForeground(Color.BLACK);
renderer.setBackground(Color.pink);
return renderer;
}
});
JPanel panel = new JPanel();
panel.setLayout(null);
panel.setBounds(10, 10, 193, 179);
panel.setBackground(new Color(102, 205, 170));
panel.add(comboBox);
panel.add(Finish);
frame.getContentPane().add(panel);
// coloring the entry field
ComboBoxEditor cedit = comboBox.getEditor();
JTextField texte = (JTextField) cedit.getEditorComponent();
texte.setBackground(Color.green);
texte.setForeground(Color.red);
cedit.setItem(texte);
comboBox.setEditor(cedit);
/* Cannot be colored when changing "true" by "false" */
comboBox.setEditable(true);
// comboBox.setEditable(false);
/* */
frame.setUndecorated(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}