1 18 package org.apache.batik.ext.swing; 19 20 import javax.swing.text.AttributeSet ; 21 import javax.swing.text.BadLocationException ; 22 import javax.swing.text.PlainDocument ; 23 24 30 public class DoubleDocument extends PlainDocument { 31 32 36 public void insertString(int offs, String str, AttributeSet a) 37 throws BadLocationException { 38 39 if (str == null) { 40 return; 41 } 42 43 String curVal = getText(0, getLength()); 45 boolean hasDot = curVal.indexOf(".")!=-1; 46 47 char[] buffer = str.toCharArray(); 49 char[] digit = new char[buffer.length]; 50 int j = 0; 51 52 if(offs==0 && buffer!=null && buffer.length>0 && buffer[0]=='-') 53 digit[j++] = buffer[0]; 54 55 for (int i = 0; i < buffer.length; i++) { 56 if(Character.isDigit(buffer[i])) 57 digit[j++] = buffer[i]; 58 if(!hasDot && buffer[i]=='.'){ 59 digit[j++] = '.'; 60 hasDot = true; 61 } 62 } 63 64 String added = new String (digit, 0, j); 66 try{ 67 StringBuffer val = new StringBuffer (curVal); 68 val.insert(offs, added); 69 if(val.toString().equals(".") || val.toString().equals("-") || val.toString().equals("-.")) 70 super.insertString(offs, added, a); 71 else{ 72 Double.valueOf(val.toString()); 73 super.insertString(offs, added, a); 74 } 75 }catch(NumberFormatException e){ 76 } 78 } 79 80 public void setValue(double d){ 81 try{ 82 remove(0, getLength()); 83 insertString(0, (new Double (d)).toString(), null); 84 }catch(BadLocationException e){ 85 } 88 } 89 90 public double getValue(){ 91 try{ 92 String t = getText(0, getLength()); 93 if(t != null && t.length() > 0){ 94 return Double.parseDouble(t); 95 } 96 else{ 97 return 0; 98 } 99 }catch(BadLocationException e){ 100 throw new Error (); 103 } 104 } 105 } 106 107 108 | Popular Tags |