I need to show numbers in jTable with exact 2 decimal places. To do this, I created my own cell editor:
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 is great for English, where the dot is used as a decimal point. But in German, it does not take a semicolon as a decimal point. Please let me know where the problem is in my code. Thanks in advance.
EDIT: This is how I worked:
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 {
source share