Search code examples
javaswingjtablecellmask

JTable - How to set text mask for cells in a specific column?


I have a JTable which the user will be able to add, edit, and remove cells (all of this without extra components besides the JTable). I want to set a custom mask (similar to JFormattedTextField) for all the cells in a specific column.

Example: The JTable has 2 columns: Time and Description. All the cells from the Time column have HH:MM mask, and the cells from the Description column don't have mask.

How can I achieve this?

Thanks.


Solution

  • Okay, it seems that I found a good solution. On this thread: Changing JTable Cell's Font while editing it There's this code on the solving answer:

    DefaultCellEditor dce = new DefaultCellEditor( textField );
    myTable.getColumnModel().getColumn(1).setCellEditor(dce);
    

    Then I adapted to use a MaskFormatter:

    table.setModel(new DefaultTableModel(new String[][] { } , new String[] {"Time", "Description"} ) );
    JFormattedTextField ftext = new JFormattedTextField();
    MaskFormatter mask;
    try {
        mask = new MaskFormatter("##:##");
        mask.install(ftext);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    table.getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(ftext));
    

    This was basically what I was looking for. Thanks for the answers.