0
\$\begingroup\$

I am wanting to use a cell editor and a DocumentFilter to prevent the user from entering certain characters into the table cells.

The columns are as follows:

  • Product ID
  • Product Description
  • Inventory Count
  • Cost
  • Minimum Quantity

For Inventory Count, Cost and Minimum Quantity I am going to use a JFormattedTextField.

How can this be improved?

public class ProductTableCellEditor extends AbstractCellEditor implements TableCellEditor
{

    private TableCellEditor editor;

    @Override
    public Object getCellEditorValue()
    {
    if (editor != null) {
        return editor.getCellEditorValue();
    }
    return null;
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
    {
    JTextField textField = new JTextField();
    textField.setFont(ApplicationStyles.TABLE_FONT);

    switch (column)
    {
    case 0:
        ((AbstractDocument) textField.getDocument()).setDocumentFilter(new ProductTableDocumentFilter());
        editor = new DefaultCellEditor(textField);
        break;
    case 1:
        ((AbstractDocument) textField.getDocument()).setDocumentFilter(new ProductTableDocumentFilter());
        editor = new DefaultCellEditor(textField);
        break;
    case 2:
        throw new UnsupportedOperationException("Not yet supported....");
    case 3:
        throw new UnsupportedOperationException("Not yet supported....");
    case 4:
        throw new UnsupportedOperationException("Not yet supported....");
    default:
        throw new UnsupportedOperationException("Not yet supported....");
    }
    return editor.getTableCellEditorComponent(table, value, isSelected, row, column);
    }
    }
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$
(AbstractDocument) textField.getDocument()

This is bad practice.

I recommend that you do one of these options:

  • The simple way would be to create a method toAbstractDocument(Document document)

  • The better way would be to create a field at TextField class such as ? extends Document document.

\$\endgroup\$
2
  • \$\begingroup\$ I am confused on how to get this to work..... \$\endgroup\$
    – Grim
    Aug 15, 2015 at 2:04
  • \$\begingroup\$ I tried this: class TextField <T extends Document> but it won't work because setDocumentFilter is of abstractDocument and not document. I would still have to cast in a method to get this to work. I could do something like this: doc = (AbstractDocument) textField.getDocument; Is that bad practice? \$\endgroup\$
    – Grim
    Aug 15, 2015 at 2:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.