001: /*
002: * NumberField.java
003: *
004: * This file is part of SQL Workbench/J, http://www.sql-workbench.net
005: *
006: * Copyright 2002-2008, Thomas Kellerer
007: * No part of this code maybe reused without the permission of the author
008: *
009: * To contact the author please send an email to: support@sql-workbench.net
010: *
011: */
012: package workbench.gui.components;
013:
014: import java.awt.Toolkit;
015: import java.text.NumberFormat;
016: import java.text.ParseException;
017: import java.util.Locale;
018:
019: import javax.swing.JTextField;
020: import javax.swing.text.AttributeSet;
021: import javax.swing.text.BadLocationException;
022: import javax.swing.text.Document;
023: import javax.swing.text.PlainDocument;
024:
025: public class NumberField extends JTextField {
026: private NumberFormat integerFormatter;
027: protected boolean allowDecimals = false;
028: protected char decimalSep = '.';
029:
030: public NumberField() {
031: super ();
032: this .init();
033: }
034:
035: public NumberField(int value, int columns) {
036: super (columns);
037: this .init();
038: integerFormatter = NumberFormat.getNumberInstance(Locale.US);
039: integerFormatter.setParseIntegerOnly(true);
040: setValue(value);
041: }
042:
043: private void init() {
044: integerFormatter = NumberFormat.getNumberInstance(Locale
045: .getDefault());
046: integerFormatter.setParseIntegerOnly(true);
047: }
048:
049: public void setDecimalChar(char aDecChar) {
050: this .decimalSep = aDecChar;
051: }
052:
053: public char getDecimalChar() {
054: return this .decimalSep;
055: }
056:
057: public void setAllowDecimals(boolean allowDec) {
058: this .allowDecimals = allowDec;
059: }
060:
061: public boolean getAllowDecimals() {
062: return this .allowDecimals;
063: }
064:
065: public int getValue() {
066: int retVal = 0;
067: try {
068: retVal = integerFormatter.parse(getText()).intValue();
069: } catch (ParseException e) {
070: // This should never happen because insertString allows
071: // only properly formatted data to get in the field.
072: Toolkit.getDefaultToolkit().beep();
073: }
074: return retVal;
075: }
076:
077: public final void setValue(int value) {
078: setText(integerFormatter.format(value));
079: }
080:
081: protected Document createDefaultModel() {
082: return new WholeNumberDocument();
083: }
084:
085: protected class WholeNumberDocument extends PlainDocument {
086: public void insertString(int offs, String str, AttributeSet a)
087: throws BadLocationException {
088: char[] source = str.toCharArray();
089: char[] result = new char[source.length];
090: int j = 0;
091:
092: for (int i = 0; i < result.length; i++) {
093: if (Character.isDigit(source[i])
094: || (allowDecimals && source[i] == decimalSep)) {
095: result[j++] = source[i];
096: } else {
097: Toolkit.getDefaultToolkit().beep();
098: //System.err.println("insertString: " + source[i]);
099: }
100: }
101: super .insertString(offs, new String(result, 0, j), a);
102: }
103: }
104: }
|