/** Handle remove. */ public void remove(int offs, int length) throws BadLocationException { int sourceLength = getLength(); // Allow user to restore uninitialized state again by removing all if (offs == 0 && sourceLength == length) { super.remove(0, sourceLength); return; } // Do custom remove String sourceText = getText(0, sourceLength); StringBuffer strBuffer = new StringBuffer(sourceText.substring(0, offs)); int counter; for (counter = offs; counter < offs + length; counter++) { // Only remove digits and intDelims char currChar = sourceText.charAt(counter); if (Character.isDigit(currChar) || currChar == intDelim) { continue; } strBuffer.append(currChar); } // Append last part of sourceText if (counter < sourceLength) { strBuffer.append(sourceText.substring(counter)); } // Set text in field super.remove(0, sourceLength); insertString(0, strBuffer.toString(), (AttributeSet) getDefaultRootElement()); // Set caret pos int newDiff = sourceLength - getLength() - 1; if (newDiff < 0) { newDiff = 0; } if (offs - newDiff < 0) { newDiff = 0; } textField.setCaretPosition(offs - newDiff); }
/** Handle string insertion. */ public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { // Store source data int sourceLength = getLength(); String sourceText = getText(0, sourceLength); StringBuffer strBuffer = new StringBuffer(sourceText); // Check if old value is zero if (offs == 0 && sourceLength > 0 && str.length() > 0) { long oldValue; try { oldValue = myFormat.parse(strBuffer.toString()).longValue(); if (oldValue == 0) { strBuffer.deleteCharAt(0); } } catch (Exception e) { } } // Now add new string strBuffer.insert(offs, str); BigDecimal value; try { value = new BigDecimal(myFormat.parse(strBuffer.toString()).doubleValue()); } catch (Exception e) { if (sourceLength > 0) { if (sourceText.startsWith(",")) { sourceText = "0" + sourceText; } value = new BigDecimal(getRealString(sourceText)); } else { value = new BigDecimal(0.0); } } // Set the new value if (textField == null) { return; } textField.setValue(new Money(value, textField.getValue().getCurrency()), false); super.remove(0, sourceLength); super.insertString(0, myFormat.format(value.doubleValue()), a); // Set caret to correct caret position if (!"".equals(sourceText)) // <=> initilized { int lengthDiff = getLength() - sourceLength; int caretPos = lengthDiff + offs; int caretDiff = sourceLength - offs; // Adjust for columns after centSperator (currently Diff < 3) if ((caretDiff > 0 && caretDiff < 3) || (value.abs().longValue() < 10 && caretPos == 0)) { caretPos += 1; } if (caretPos < 0) { caretPos = 0; } textField.setCaretPosition(caretPos); } else { textField.setCaretPosition(1); } }