Question

I have a JTable, whose cell editors are JSpinners. I'm using a custom cell editor class to accomplish this. I have a few other components in my JPanel. My problem arises when the user is editing one of the cells (i.e. a JSpinner has focus) and then interacts with one of the other components without first pressing enter or losing focus. I want the JSpinner to immediately lose focus and commit the changes before running the code associated with the other components, but instead the JSpinner just retains its focus.

Ideally, I would like the JSpinner to lose focus immediately whenever the user clicks anywhere but inside the JSpinner itself. Here's my custom editor class:

public class PhyMappingTableCellEditor extends AbstractCellEditor implements TableCellEditor {
    final JSpinner spinner = new JSpinner();

    public PhyMappingTableCellEditor(ArrayList<String> phys) {
        spinner.setModel(new SpinnerListModel(phys));
        spinner.setBorder(new EmptyBorder(0,0,0,0)); 
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected,
        int row, int column) {
        spinner.setValue(value);
        return spinner;
    }

    @Override
    public Object getCellEditorValue() {
        return spinner.getValue();
    }
}

Thanks in advance!

Was it helpful?

Solution

Assuming your custom editor works correctly when you tab from cell to cell then the problem is that you need to manually stop editing on the cell when the table loses focus.

Check out Table Stop Editing. It shows how to stop editing on a cell when the table loses focus. The solution will work for any cell that is being edited, not just your custom editor.

OTHER TIPS

I had a similar problem. If the spinner value was edited using the keyboard and then you clicked another table cell with out first pressing enter, the edits were lost. I solved it by overriding AbstractCellEditor.stopCellEditing() like this:

@Override
public boolean stopCellEditing() {
    try {
        spinner.commitEdit();
    }
    catch (ParseException ex) {
        // Do nothing
    }
    return super.stopCellEditing();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top