Here's another hack, due to Michael Grimes, which shouldn't be affected by the particular look and feel. The trick is to make the combo box editable; the JTextField
which is exposed as the editor supports the setDisabledTextColor
method. And since you're disabling the combo box, it doesn't matter that it's editable! The code that I'm using to do this (translated from Scala) is the following:
JComboBox cb = ...;
...
cb.setEditable(true);
ComboBoxEditor editor = cb.getEditor()
JTextField etf = (JTextField)etf.getEditorComponent()
etf.setDisabledTextColor(UIManager.getColor("ComboBox.foreground"));
etf.setBackground(UIManager.getColor("ComboBox.background"));
// editor.setItem(format(obj));
cb.setEnabled(false);
The cast is guaranteed to succeed here because we're using a BasicComboBoxEditor
, whose docs say "The editor is implemented as a JTextField." The commented-out line occurs because I'm using a custom renderer which prints integers with extra text surrounding them; calling setItem
allows me to specify a similar string, and is necessary because the editor ignores the custom renderer. If you're using the default renderer, then you don't need to worry about that line; on the other hand, if you're using a more complicated renderer, then you might need to do something else entirely.
Despite the fact that this is a horrific kludge, it works, and it doesn't seem to rely on any implementation-defined features. The two places I could imagine this breaking are (a), if an editable combo box looks very different from an uneditable one (for instance, my first attempt didn't change the background color of the text field, which made it look wrong), or (b) if BasicComboBoxEditor
stopped returning a JTextField
(which seems less likely). But so far, it's serving my purposes.
setForeground
, so it's sightly more efficient to leave it unchanged and overwrite the other. – Maffei