Re: Custom ComboBox Editor in JTable focus issue

From: John Wheeler (johnwheeler79_at_msn.com)
Date: 11/26/03


Date: 26 Nov 2003 11:25:14 -0800

I created a table cell editor that extends JComboBox and implements
TableCellEditor. It's constructor installs my custom key selection
manager (I followed the JScrollBar sample from Chapter 15 of Eckstein,
Loy, and Wood) . I got what I wanted, but I don't know why. my
fireEditingStopped implementation is similar to
AbstractTableCellEditor's implementation. I guess I don't understand
the protocol these components use, but I am satisfied with how things
are going. Are you aware of any ramifications I should know about?

public class AshtonComboBoxTableCellEditor extends JComboBox
implements TableCellEditor {

    protected transient Vector listeners;
    protected transient Object origValue;

    public AshtonComboBoxTableCellEditor(Vector parts) {
        setKeySelectionManager(new AshtonComboBoxKeySM());
        listeners = new Vector();
        for (int i=0, n=parts.size(); i<n; i++)
            addItem(parts.get(i));
    }

    public Component getTableCellEditorComponent(JTable table, Object
value,
                                                 boolean isSelected,
                                                 int row, int column)
{
        if (value == null)
            return this;

        setSelectedItem(value);
        table.setRowSelectionInterval(row, row);
        table.setColumnSelectionInterval(column, column);
        origValue = getSelectedItem();

        return this;
    }

    public Object getCellEditorValue() {
        return getSelectedItem();
    }

    public boolean isCellEditable(EventObject anEvent) {
        return true;
    }

    public boolean shouldSelectCell(EventObject anEvent) {
        return true;
    }

    public boolean stopCellEditing() {
        fireEditingStopped();
        return true;
    }

    public void cancelCellEditing() {
        fireEditingCancelled();
    }

    public void addCellEditorListener(CellEditorListener l) {
        listeners.addElement(l);
    }

    public void removeCellEditorListener(CellEditorListener l) {
        listeners.removeElement(l);
    }

    protected void fireEditingCancelled() {
        setSelectedItem(origValue);
        ChangeEvent ce = new ChangeEvent(this);
        for (int i=listeners.size()-1; i>=0; i--)
            ((CellEditorListener)listeners.elementAt(i)).editingCanceled(ce);
    }

    protected void fireEditingStopped() {
        ChangeEvent ce = new ChangeEvent(this);
        for (int i=listeners.size()-1; i>=0; i--)
            ((CellEditorListener)listeners.elementAt(i)).editingStopped(ce);
    }