编辑单元格值时以十进制格式显示数据

时间:2011-12-28 10:09:32

标签: java swing jtable

在JTable中编辑单元格值时,它的值突然以指数形式出现(即1.7E10),而不是以普通的用户友好形式显示。

如何在编辑单元格值时更改数字格式?

...

解决方案非常简单,必须创建我自己的TableCellEditor:

 public static class Double2DecimalEditor extends AbstractCellEditor implements TableCellEditor{

    private static final long serialVersionUID = 1L;
    private JComponent component = new JTextField();
    private NumberFormat nf;

    @Override
    public Object getCellEditorValue() {
        System.out.println("getCellEditorValue");
        NumberFormat nf = new DecimalFormat("#,###.###");
        String text = ((JTextField)component).getText();
        System.out.println("TEXT = " + ((JTextField)component).getText());
        return nf.format(Double.parseDouble(text));
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        System.out.println("getCellEditorComponent");
        Double data = Double.valueOf(value.toString().replace(",", ""));
        NumberFormat nf = new DecimalFormat("#.###");
        ((JTextField)component).setText(nf.format(data));
        ((JTextField)component).setHorizontalAlignment(SwingConstants.RIGHT);
        return component;
    }
}

感谢大家的建议!

2 个答案:

答案 0 :(得分:3)

这里是SSCCE,它演示了Double的问题(并且通过实现NumberRenderer),

enter image description here

只是我的好奇心,我离开回答这个问题,也许有更好的解决方法,如果有任何存在

import java.awt.*;
import java.math.RoundingMode;
import java.text.NumberFormat;
import javax.swing.*;
import javax.swing.table.*;

public class Back2DefaultSortingTest {

    private static JTable makeSampleTable() {
        String[] columnNames = {"String", "Integer", "Boolean", "Double"};
        Object[][] data = {{"AAA", 12, true, 111111111111.15},
            {"BBB", 1, false, 11199999111.15}, {"CCC", 2, true, 1155555511111.15},};
        DefaultTableModel m = new DefaultTableModel(data, columnNames) {

            private static final long serialVersionUID = 1L;

            @Override
            public Class<?> getColumnClass(int column) {
                return getValueAt(0, column).getClass();
            }
        };
        JTable table = new JTable(m);
        TableColumnModel tm = table.getColumnModel();
        tm.getColumn(3).setCellRenderer(new Double2DecimalRenderer());
        return table;
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                createAndShowGUI();
            }
        });
    }

    public static void createAndShowGUI() {
        JPanel p = new JPanel(new BorderLayout());
        p.add(new JScrollPane(makeSampleTable()));
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.getContentPane().add(p);
        frame.setSize(320, 240);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static class Double2DecimalRenderer extends DefaultTableCellRenderer {

        private static final long serialVersionUID = 1L;
        private int precision = 0;
        private Number numberValue;
        private NumberFormat nf;

        public Double2DecimalRenderer() {
            super();
            setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
            precision = 0;
            nf = NumberFormat.getNumberInstance();
            nf.setMinimumFractionDigits(2);
            nf.setMaximumFractionDigits(2);
            nf.setRoundingMode(RoundingMode.HALF_UP);
        }

        @Override
        public void setValue(Object value) {
            if ((value != null) && (value instanceof Number)) {
                numberValue = (Number) value;
                value = nf.format(numberValue.doubleValue());
            }
            super.setValue(value);
        }
    }

    private Back2DefaultSortingTest() {
    }
}

答案 1 :(得分:2)

据我所知,这一行破坏了你的代码

textField.setText((value != null) ? value.toString() : "");

这发生在JTable使用的javax.swing.DefaultCellEditor#DefaultCellEditor中。

您必须添加自己的应用格式的编辑器。

也应该类似

table.setDefaultEditor(Double.class, new DefaultCellEditor(new JTextField())
    {
      public Component getTableCellEditorComponent( JTable table, Object value,
                                                    boolean isSelected,
                                                    int row, int column )
      {
        String formattedvalue = formatyourvalue(value);
        delegate.setValue(formattedvalue);
        return editorComponent;
      }
    });

应用于示例,您可以使用

更改makeTable
  private static JTable makeSampleTable()
  {
    String[] columnNames = {"String", "Integer", "Boolean", "Double"};
    Object[][] data = {{"AAA", 12, true, 111111111111.15},
                       {"BBB", 1, false, 11199999111.15}, {"CCC", 2, true, 1155555511111.15},};
    DefaultTableModel m = new DefaultTableModel(data, columnNames)
    {

      private static final long serialVersionUID = 1L;

      @Override
      public Class<?> getColumnClass( int column )
      {
        return getValueAt(0, column).getClass();
      }
    };
    JTable table = new JTable(m);
    TableColumnModel tm = table.getColumnModel();
    tm.getColumn(3).setCellRenderer(new Double2DecimalRenderer());
    table.setDefaultEditor(Double.class, new DefaultCellEditor(new JTextField())
    {
      public Component getTableCellEditorComponent( JTable table, Object value,
                                                    boolean isSelected,
                                                    int row, int column )
      {
        NumberFormat nf;
        nf = NumberFormat.getNumberInstance();
        nf.setMinimumFractionDigits(2);
        nf.setMaximumFractionDigits(2);
        if ( ( value != null ) && ( value instanceof Number ) )
          {
          Number numberValue = (Number) value;
          delegate.setValue(nf.format(numberValue.doubleValue()));
          }
        else
          {
          delegate.setValue(value);
          }
        return editorComponent;
      }
    });
    return table;
  }