001: package net.sourceforge.squirrel_sql.fw.gui;
002:
003: /*
004: * Copyright (C) 2001-2003 Colin Bell
005: * colbell@users.sourceforge.net
006: *
007: * This library is free software; you can redistribute it and/or
008: * modify it under the terms of the GNU Lesser General Public
009: * License as published by the Free Software Foundation; either
010: * version 2.1 of the License, or (at your option) any later version.
011: *
012: * This library is distributed in the hope that it will be useful,
013: * but WITHOUT ANY WARRANTY; without even the implied warranty of
014: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
015: * Lesser General Public License for more details.
016: *
017: * You should have received a copy of the GNU Lesser General Public
018: * License along with this library; if not, write to the Free Software
019: * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
020: */
021: import java.awt.Toolkit;
022:
023: import javax.swing.JTextField;
024: import javax.swing.text.AttributeSet;
025: import javax.swing.text.BadLocationException;
026: import javax.swing.text.Document;
027: import javax.swing.text.PlainDocument;
028:
029: /**
030: * This class is a <CODE>TextField</CODE> that only allows integer
031: * values to be entered into it.
032: *
033: * @author <A HREF="mailto:colbell@users.sourceforge.net">Colin Bell</A>
034: */
035: public class IntegerField extends JTextField {
036: /**
037: * Default ctor.
038: */
039: public IntegerField() {
040: super ();
041: }
042:
043: /**
044: * Ctor specifying the field width.
045: *
046: * @param cols Number of columns.
047: */
048: public IntegerField(int cols) {
049: super (cols);
050: }
051:
052: /**
053: * Retrieve the contents of this field as an <TT>int</TT>.
054: *
055: * @return the contents of this field as an <TT>int</TT>.
056: */
057: public int getInt() {
058: final String text = getText();
059: if (text == null || text.length() == 0) {
060: return 0;
061: }
062: return Integer.parseInt(text);
063: }
064:
065: /**
066: * Set the contents of this field to the passed <TT>int</TT>.
067: *
068: * @param value The new value for this field.
069: */
070: public void setInt(int value) {
071: setText(String.valueOf(value));
072: }
073:
074: /**
075: * Create a new document model for this control that only accepts
076: * integral values.
077: *
078: * @return The new document model.
079: */
080: protected Document createDefaultModel() {
081: return new IntegerDocument();
082: }
083:
084: /**
085: * This document only allows integral values to be added to it.
086: */
087: static class IntegerDocument extends PlainDocument {
088: public void insertString(int offs, String str, AttributeSet a)
089: throws BadLocationException {
090: if (str != null) {
091: try {
092: Integer.decode(str);
093: super .insertString(offs, str, a);
094: } catch (NumberFormatException ex) {
095: Toolkit.getDefaultToolkit().beep();
096: }
097: }
098: }
099: }
100: }
|