0

I have a class that I use for creating JSpinner box based column in a JTable. However, I have an issue that when I edit values in new row the old value of the spinner box is shown in the new cell. For example, if I made value in row 1 to be 3, and then move to row 2, the min value of spinner starts at 3, instead of 0. Can somebody suggest a way to modify this behavior?

I was thinking may be I need a separate spinner box for each row and I will have to maintain a map of row number to spinner box, however, I have a feeling that there should be a better solution available.

public class SpinnerColumn extends AbstractCellEditor implements TableCellEditor, TableCellRenderer {
    private final JSpinner spinner = new JSpinner();
    private JTable table;

    public SpinnerColumn(JTable table, int column)
    {
        this.table = table;
        table.getColumnModel().getColumn(column).setCellEditor(this);
    }

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

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

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value,
        boolean isSelected, boolean hasFocus, int row, int column)
    {
        return spinner;
    }
}
Kapil Sharma
  • 1,412
  • 1
  • 15
  • 19
  • 1
    In getCellEditorValue, call spinner.commit() to commit the value in the spinner to the model. This occurs because the getCellEditorValue method is called before the spinner is notified of the lost of focus – MadProgrammer Oct 21 '15 at 20:15
  • 1
    Also,,make sure you've implemented setValueAt in your TableModel properly – MadProgrammer Oct 21 '15 at 20:17
  • Can you please elaborate on the setValueAt method in TableModel? Would I need to override that method in my own implementation of DefaultTableModel? – Kapil Sharma Oct 21 '15 at 23:08
  • If you're using a `DefaultTableModel`, then it should be taking care of it, but you didn't provide that information so I just made a point of it – MadProgrammer Oct 21 '15 at 23:10

0 Answers0