1
votes

Say I have following columns in my Jtable:

{"Item", "Price"}

I want format the price column to "0.00" format. But if user enter an illegal string, then keep the original value of the cell. ex, when the price is "1.23", but when user want to enter "abc", then the cell should still be "1.23"

How could I do this?

Thanks

4

4 Answers

2
votes

Let's split your big problemn into smaller ones.

First, you want to have items of your Price column to be displayed according to a specified format, which you can achieve using a TableCellRenderer (which, when rendering numbers, will use a NumberFormat to display the correct number of decimals). As your table has only two columns of different types, the simplest solution is to use JTable#setDefaultRenderer(Class<?> columnClass, TableCellRenderer renderer). This way, your numbers will always be displayed using the correct number of decimals.

Second, for your edition issue, the same solution can be rather elegant : call JTable#setDefaultEditor(java.lang.Class, javax.swing.table.TableCellEditor) and set as editor a component one that will, before commiting change to your table model, ensure the new value is a valid number (valid of course according to your rules).

2
votes

A JTable supports this by default. The table will choose the renderer/editor based on the data stored in each column. So all you need to do is override the getColumnClass(...) method to return Double.class. Then when you edit a cell the editor will make sure the value entered is a valid number.

If you want more control over how the number is formatted then you can use Table Format Renderer.

1
votes

JFormattedTextField works the way you describe so just create a new CellEditor that extends JFormattedTextField.

0
votes

Put the formatting command into a try/catch block. If the operation fails with an NumberFormatException, cancel the edit.

Using your original code, make a few minor changes:

public void setValue(Object value) {
   NumberFormat formatter = new DecimalFormat("0.00");
   String s = null;
   try {
      s = formatter.format(Integer.parseInt((String)value));
      if (null != s) setText(s);
   } catch (NumberFormatException ex) {
      // what could I do here?
      // You could display a warning JOptionPane and/or output to System.out
   }
}