PDA

View Full Version : PercentField



sjardine
3 Feb 2009, 9:32 AM
Here is a extension of the NumberField to allow for entering percentage values. For this field when the user enters 1 = 1.00%, 0.25 = 0.25%, 50% = 50.00% etc. The underlying Double value returns 0.01, 0.0025, 0.50, etc.

I took most of the code for this from a previous post dealing with currency values found here:
https://extjs.com/forum/showthread.php?t=48944&highlight=NumberField+Currency
Thanks!



public class PercentField extends NumberField {

NumberFormat numberFormat = NumberFormat.getDecimalFormat();

NumberFormat percentFormat = NumberFormat.getFormat("#,##0.00%;(#,##0.00%)");

public PercentField() {
setFormat(percentFormat);
String formatchars = percentFormat.format(10000.0);
String basechars = "1234567890";
for (int i = 0; i < formatchars.length(); i++) {
if (!Character.isDigit(formatchars.charAt(i))) {
basechars += formatchars.charAt(i);
}
}
setBaseChars(basechars);
}

@Override
public Number getValue() {
Number v = super.getValue();
if (v != null && isRendered()) {
v = (v.doubleValue() / 100);
}
return v;
}

@Override
protected void onBlur(ComponentEvent arg0) {
if (getRawValue() != null && !getRawValue().equals("")) {
Double rawvalue = 0d;
try {
rawvalue = percentFormat.parse(getRawValue());
} catch (NumberFormatException e) {
try {
rawvalue = numberFormat.parse(getRawValue());
} catch (NumberFormatException e2) {
rawvalue = null;
}
}
if (rawvalue != null) {
setRawValue(percentFormat.format(rawvalue / 100));
} else throw new NumberFormatException();
}
super.onBlur(arg0);
}

}