01: /*
02: * CharLimitedTextField.java
03: *
04: * Copyright (C) 2002, 2003, 2004, 2005, 2006 Takis Diakoumis
05: *
06: * This program is free software; you can redistribute it and/or
07: * modify it under the terms of the GNU General Public License
08: * as published by the Free Software Foundation; either version 2
09: * of the License, or any later version.
10: *
11: * This program is distributed in the hope that it will be useful,
12: * but WITHOUT ANY WARRANTY; without even the implied warranty of
13: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14: * GNU General Public License for more details.
15: *
16: * You should have received a copy of the GNU General Public License
17: * along with this program; if not, write to the Free Software
18: * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19: *
20: */
21:
22: package org.underworldlabs.swing;
23:
24: import java.awt.Toolkit;
25: import javax.swing.JTextField;
26: import javax.swing.text.AttributeSet;
27: import javax.swing.text.BadLocationException;
28: import javax.swing.text.Document;
29: import javax.swing.text.PlainDocument;
30:
31: /* ----------------------------------------------------------
32: * CVS NOTE: Changes to the CVS repository prior to the
33: * release of version 3.0.0beta1 has meant a
34: * resetting of CVS revision numbers.
35: * ----------------------------------------------------------
36: */
37:
38: /**
39: *
40: * @author Takis Diakoumis
41: * @version $Revision: 1.4 $
42: * @date $Date: 2006/05/14 06:56:07 $
43: */
44: public class CharLimitedTextField extends JTextField {
45:
46: private int maxLength;
47: private CharLimitedDocument charLimitedDocument;
48:
49: public CharLimitedTextField(int maxLength) {
50: this .maxLength = maxLength;
51: if (charLimitedDocument == null) {
52: charLimitedDocument = new CharLimitedDocument();
53: }
54: }
55:
56: public void setMaxLength(int maxLength) {
57: this .maxLength = maxLength;
58: }
59:
60: public int getMaxLength() {
61: return maxLength;
62: }
63:
64: protected Document createDefaultModel() {
65: if (charLimitedDocument == null) {
66: charLimitedDocument = new CharLimitedDocument();
67: }
68: return charLimitedDocument;
69: }
70:
71: class CharLimitedDocument extends PlainDocument {
72:
73: private Toolkit toolkit;
74:
75: public CharLimitedDocument() {
76: toolkit = Toolkit.getDefaultToolkit();
77: }
78:
79: public void insertString(int offs, String str, AttributeSet a)
80: throws BadLocationException {
81: if (getLength() >= maxLength) {
82: toolkit.beep();
83: return;
84: }
85: super.insertString(offs, str, a);
86: }
87: }
88:
89: }
|