I am not sure if this is the right way to do this but I think so. I have tried to use DecimalFormat but I cant understand it. Can someone help me? Is this the correct way to do this DefaultCellEditor + DecimalFormat?
Asked
Active
Viewed 1,620 times
0
-
1Talk more about write way. Is this a read way for me? – Roman C Nov 07 '12 at 11:10
-
1@AndrewThompson, you edited and let "write way" stay there!? – HericDenis Nov 07 '12 at 11:12
-
@user1761818, you should put here what you tried. – HericDenis Nov 07 '12 at 11:14
-
@HericDenis 1) I did not edit (or carefully read) the body, just the tags. 2) When I do, it is mostly the 'red squiggly underlines' that FF thinks are wrongly spelled, that draws my eye to them. So even if I had edited the body, it is unlikely I would have noticed the difference between 'write' and 'right'. ;) – Andrew Thompson Nov 07 '12 at 11:15
-
1Have a look at [How to Use Tables](http://docs.oracle.com/javase/tutorial/uiswing/components/table.html) in particular [Using an Editor to Validate User-Entered Text](http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#validtext) – MadProgrammer Nov 07 '12 at 11:15
-
That's ok @AndrewThompson, I was just annoying you bro (: – HericDenis Nov 07 '12 at 12:08
1 Answers
4
override column class by using
Double.Class
for
XxxTableCellEditor
to useJFormattedTextField
orJSpinner
as Editor, formatted by proper methods fromNumberFormat
orDecimalNumberFormat
, including roundingset
DefaultTableCellRenderer
for desired columyou can to set (too) proper
Rounding method
fromNumberFormat
for example
TableColumnModel tcmAmount = myTable.getColumnModel();
TableColumn tcAmount = tcmAmount.getColumn(2);
tcAmount.setCellRenderer(new DRManMmAmount(1)); // decimal precision
and
private static class DRManMmAmount extends DefaultTableCellRenderer {
private static final long serialVersionUID = 1L;
int precision = 0;
Number numberValue;
NumberFormat nf;
public DRManMmAmount(int p_precision) {
super();
setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
precision = p_precision;
nf = NumberFormat.getNumberInstance();
nf.setMinimumFractionDigits(p_precision);
nf.setMaximumFractionDigits(p_precision);
//nf.setMinimumFractionDigits(2);
//nf.setMaximumFractionDigits(2);
}
@Override
public void setValue(Object value) {
if ((value != null) && (value instanceof Number)) {
numberValue = (Number) value;
value = nf.format(numberValue.doubleValue());
}
super.setValue(value);
}
}