what's the correct way to set the disabled foreground color of a jcombobox? i don't want to set the disabled color for the entire ui to the same color, but for one jcombobox specifically. i searched the web and found many posts with the same question, but no real solution. this one has been giving me nightmares and i thought i'd share what i've found. the solution seems to be quite simple: wrap the combobox label in a panel. that way the panel gets the disabled colors, but the coloring of the label of the combobox remains. here's the solution in short in case others need it:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
public class MyComboBox extends JComboBox {
public MyComboBox() {
super();
setRenderer( new ColorCellRenderer());
}
public static void main(String s[]) {
JFrame frame = new JFrame("ComboBox Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JComboBox cb = new MyComboBox();
cb.addItem( "ComboBox Item 1");
cb.addItem( "ComboBox Item 2");
cb.addItem( "ComboBox Item 3");
cb.setForeground( Color.blue);
final JButton bt = new JButton ("disable");
bt.addActionListener( new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cb.setEnabled( !cb.isEnabled());
if( !cb.isEnabled()) {
cb.setForeground( Color.red);
bt.setText( "enable");
} else {
cb.setForeground( Color.blue);
bt.setText( "disable");
}
}
});
frame.getContentPane().setLayout( new FlowLayout());
frame.getContentPane().add( bt);
frame.getContentPane().add( cb);
frame.pack();
frame.setVisible(true);
}
class ColorCellRenderer implements ListCellRenderer {
protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) defaultRenderer
.getListCellRendererComponent(list, value, index,
isSelected, cellHasFocus);
JPanel wrapper = new JPanel();
wrapper.setLayout( new BorderLayout());
wrapper.add( label, BorderLayout.CENTER);
return wrapper;
}
}
}
if anyone knows a way to remove the dropdown button of a disabled combobox without leaving a blank space when you simply hide the button, feel free to extend this :-)
Edited by: Lofi on Mar 20, 2010 10:46 PM