Java JTable 单元格编辑器编号格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6556651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 07:42:40  来源:igfitidea点击:

JTable cell editor number format

javaswingjtablenumber-formattingtablecelleditor

提问by Khalid Amin

I need to show numbers in jTable with exact 2 decimal places. To accomplish this I have created a custom cell editor as:

我需要在 jTable 中显示精确到 2 个小数位的数字。为此,我创建了一个自定义单元格编辑器:

public class NumberCellEditor extends DefaultCellEditor {
    public NumberCellEditor(){
        super(new JFormattedTextField());
    }

    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        JFormattedTextField editor = (JFormattedTextField) super.getTableCellEditorComponent(table, value, isSelected, row, column);

        if (value!=null){
            DecimalFormat numberFormat = new DecimalFormat("#,##0.00;(#,##0.00)");
            editor.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(numberFormat)));
            Number num = (Number) value;  
            String text = numberFormat.format(num);
            editor.setHorizontalAlignment(SwingConstants.RIGHT);
            editor.setText(text);
        }
        return editor;
    }
}

This cell editor works perfect for English locale where a dot is used as decimal point. But in German locale, it doesn't accept values with comma as a decimal point. Please let me know where there is a problem in my code. Thanks in advance.

此单元格编辑器非常适合使用点作为小数点的英语语言环境。但是在德语语言环境中,它不接受以逗号作为小数点的值。请让我知道我的代码哪里有问题。提前致谢。

EDIT: Here is how I got it working:

编辑:这是我的工作方式:

public class NumberCellEditor extends DefaultCellEditor {
public NumberCellEditor(){
    super(new JFormattedTextField());
}

@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
    JFormattedTextField editor = (JFormattedTextField) super.getTableCellEditorComponent(table, value, isSelected, row, column);

    if (value instanceof Number){
        Locale myLocale = Locale.getDefault(); 

        NumberFormat numberFormatB = NumberFormat.getInstance(myLocale);
        numberFormatB.setMaximumFractionDigits(2);
        numberFormatB.setMinimumFractionDigits(2);
        numberFormatB.setMinimumIntegerDigits(1);

        editor.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(
                        new NumberFormatter(numberFormatB)));

        editor.setHorizontalAlignment(SwingConstants.RIGHT);
        editor.setValue(value);
    }
    return editor;
}

@Override
public boolean stopCellEditing() {
    try {
        // try to get the value
        this.getCellEditorValue();
        return super.stopCellEditing();
    } catch (Exception ex) {
        return false;
    }

}

@Override
public Object getCellEditorValue() {
    // get content of textField
    String str = (String) super.getCellEditorValue();
    if (str == null) {
        return null;
    }

    if (str.length() == 0) {
        return null;
    }

    // try to parse a number
    try {
        ParsePosition pos = new ParsePosition(0);
        Number n = NumberFormat.getInstance().parse(str, pos);
        if (pos.getIndex() != str.length()) {
            throw new ParseException(
                    "parsing incomplete", pos.getIndex());
        }

        // return an instance of column class
        return new Float(n.floatValue());

    } catch (ParseException pex) {
        throw new RuntimeException(pex);
    }
}
}

采纳答案by Hovercraft Full Of Eels

Use the locale to your advantage:

充分利用语言环境:

  //Locale myLocale = Locale.GERMANY;  //... or better, the current Locale

  Locale myLocale = Locale.getDefault(); // better still

  NumberFormat numberFormatB = NumberFormat.getInstance(myLocale);
  numberFormatB.setMaximumFractionDigits(2);
  numberFormatB.setMinimumFractionDigits(2);
  numberFormatB.setMinimumIntegerDigits(1);

  edit.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(
                    new NumberFormatter(numberFormatB)));

回答by mKorbel

for example

例如

import java.text.NumberFormat;
import java.math.RoundingMode;
import javax.swing.table.DefaultTableCellRenderer;


public class SubstDouble2DecimalRenderer extends DefaultTableCellRenderer {

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

    public SubstDouble2DecimalRenderer(int p_precision) {
        super();
        setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        precision = p_precision;
        nf = NumberFormat.getNumberInstance();
        nf.setMinimumFractionDigits(p_precision);  
        nf.setMaximumFractionDigits(p_precision);
        nf.setRoundingMode(RoundingMode.HALF_UP);  
    }

    public SubstDouble2DecimalRenderer() {
        super();
        setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        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);
    }
}

回答by Eng.Fouad

Try

尝试

DecimalFormat numberFormat = new DecimalFormat("\d*([\.,\,]\d{0,2})?");

回答by user2316705

Just change #,###,###,##0.00with #.###.###.##0,00

只是改变#,###,###,##0.00#.###.###.##0,00