1 package sellwin.gui; 2 3 import javax.swing.*; 4 import javax.swing.text.*; 5 6 import java.awt.Toolkit ; 7 import java.text.*; 8 import java.util.Locale ; 9 10 14 18 public class DoubleNumberField extends JTextField { 19 private Toolkit toolkit; 20 private NumberFormat doubleFormatter; 21 22 27 public DoubleNumberField(double value, int columns) { 28 super(columns); 29 toolkit = Toolkit.getDefaultToolkit(); 30 doubleFormatter = DecimalFormat.getNumberInstance(Locale.US); 31 setValue(value); 32 } 33 34 38 public final double getValue() { 39 double retVal = 0.00; 40 try { 41 retVal = doubleFormatter.parse(getText()).doubleValue(); 42 } catch (ParseException e) { 43 toolkit.beep(); 46 } 47 return retVal; 48 } 49 50 54 public final void setValue(double value) { 55 setText(doubleFormatter.format(value)); 56 } 57 58 62 protected final Document createDefaultModel() { 63 return new DoubleNumberDocument(); 64 } 65 66 69 protected class DoubleNumberDocument extends PlainDocument { 70 public void insertString(int offs, 71 String str, 72 AttributeSet a) 73 throws BadLocationException { 74 char[] source = str.toCharArray(); 75 char[] result = new char[source.length]; 76 int j = 0; 77 78 for (int i = 0; i < result.length; i++) { 79 if (Character.isDigit(source[i]) || (source[i] == '.')) 80 result[j++] = source[i]; 81 else { 82 toolkit.beep(); 83 System.err.println("insertString: " + source[i]); 84 } 85 } 86 super.insertString(offs, new String (result, 0, j), a); 87 } 88 } 89 } 90 | Popular Tags |