Search code examples
javaswingjtablelook-and-feeltablecelleditor

Custom cell editor can't accommodate text in Nimbus Look and Feel


I want to validate user input in a table cell, and I use the Nimbus Look and Feel. Here is the code of a cell editor that validates integer input: WholeNumberField It extends JTextField and adds input validation.

When I set it for the column it works fine, but it can't accommodate the text:

text cut

When I use default cell editor, it all looks fine:

normal look

How can I this editor look like the default editor?


Solution

  • The WholeNumberField is old code. If you really want to do custom validation then you should be using a DocumentFilter.

    However, in this case, there is no need to create a custom editor. JTable already supports an editor to validate numbers. You just need to override the isCellEditable(...) method of the JTable or the TableModel to return Integer.Class and the proper renderer and editor will be used.

    Edit: Just noticed my suggestion is incorrect.

    1. you need to override getColumnClass(...) to return Integer.class so the proper renderer/editor can be used.
    2. the isCellEditable(...) method is used to determine if you can edit a cell.