开发者

Format a Jtable Cell, if illegal format, then do nothing

开发者 https://www.devze.com 2023-02-07 20:08 出处:网络
Say I have following columns in my Jtable: {\"Item\", \"Price\"} I want format the price column to \"0.00\" format.

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 ille开发者_开发百科gal 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


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).


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.


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


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
   }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消