Ein komplettes Testprogramm ist schwierig, weil es aus vielen Fragmenten besteht, die ich im Netz gefunden habe. Das Ganze ist inzwischen recht umfangreich.
Ich habe ein weiteres Suchmaschinen-Fundstück ausprobiert. Nach einigen kleinen Anpassungen funktioniert nun fast alles.
Der aktuelle Code des CellEditors sieht so aus:
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);
editor.setFont(table.getFont());
editor.setBorder(null);
if (value instanceof Number) {
NumberFormat numberFormat = NumberFormat.getInstance(Locale.getDefault());
numberFormat.setMaximumFractionDigits(1);
numberFormat.setMinimumFractionDigits(0);
numberFormat.setMinimumIntegerDigits(1);
editor.setFormatterFactory(new DefaultFormatterFactory(new NumberFormatter(numberFormat)));
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 || str.trim().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 n;
}
catch (ParseException pex) {
throw new RuntimeException(pex);
}
}
}```