I am programming an editable combobox in a JFrame Form, but i want to change te background color.
How the program works: If i click the button \"press\", then the co
It works for me to change the color of a selected item in JComboBox.
JComboBox cmb = new JComboBox();
cmb.setEditable(true);
cmb.setEditor(new WComboBoxEditor(getContentPane().getBackground()));
// To change the arrow button's background
cmb.setUI(new BasicComboBoxUI(){
protected JButton createArrowButton()
{
BasicArrowButton arrowButton = new BasicArrowButton(BasicArrowButton.SOUTH, null, null, Color.GRAY, null);
return arrowButton;
}
});
cmb.setModel(new DefaultComboBoxModel(new String[] { "a", "b", "c" }));
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionListener;
import javax.swing.ComboBoxEditor;
import javax.swing.JTextField;
public class WComboBoxEditor implements ComboBoxEditor
{
JTextField tf;
public WComboBoxEditor(Color background)
{
tf = new JTextField();
tf.setBackground(background);
tf.setBorder(null);
}
public Component getEditorComponent()
{
return tf;
}
public void setItem(Object anObject)
{
if (anObject != null)
{
tf.setText(anObject.toString());
}
}
public Object getItem()
{
return tf.getText();
}
public void selectAll()
{
tf.selectAll();
}
public void addActionListener(ActionListener l)
{
tf.addActionListener(l);
}
public void removeActionListener(ActionListener l)
{
tf.removeActionListener(l);
}
}
If you'd like to change the color of items in JCombobox except for a selected one, customize ListCellRenderer.