How to change the color of a cell in a table using ComboBox as editor
I have a table using ComboBox as editor. (Cells in the same row share one ComboBox). And, I set ComboBox to be editable. Now the problem is: how can I change the fore/background color of the cell when the typed string is not in the combobox list? For example, the combobox contains "Snowboarding" and "Rowing", and if I type "Teaching", I want the fore or background color of the cell to be changed to red. How can I do this? Thanks a lot!
-
Followings are some codes I written:
// a default cell editor
JComboBox combobox = new JComboBox();
combobox.setEditable(true);
comboBox.addItem("Snowboarding");
comboBox.addItem("Rowing");
DefaultCellEditor dce = new DefaultCellEditor(combobox);
//a jtable
private DefaultTableModel table_model = new DefaultTableModel();
private JTable table = new JTable(table_model){
...
public TableCellEditor getCellEditor(int rowIndex, int colIndex) {
return dce;
}
...
}
[1012 byte] By [
YuDanga] at [2007-10-3 3:13:07]

I think to do this, you need to create a JTextField and set it as the combo's editor. Then set the background or foreground color of the JTextField while they're typing by adding a DocumentListener to the JTextField's document.
JTextField txtField = new JTextField();
combo.setEditor(txtField);
txtField.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent ev) {
// Check if txtField.getText() is not in the combo's list.
// See the API for how to implement DocumentListener
}
});
I'm sorry, my above reply is wrong because you can't set a combo's editor to a JTextField. Instead, you cast the combo's edtior's editor component into a JTextField. This works:
JComboBox combo = new JComboBox();
combo.setEditable(true);
final JTextField editor = (JTextField)combo.getEditor().getEditorComponent();
editor.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
String txt = editor.getText();
if (txt != null && txt.equals("Hello")) {
editor.setForeground(Color.RED);
} else {
editor.setForeground(Color.BLACK);
}
}
public void removeUpdate(DocumentEvent e) {
String txt = editor.getText();
if (txt != null && txt.equals("Hello")) {
editor.setForeground(Color.RED);
} else {
editor.setForeground(Color.BLACK);
}
}
public void changedUpdate(DocumentEvent e) { }
});