01: package net.sourceforge.squirrel_sql.fw.gui;
02:
03: /*
04: * Copyright (C) 2001-2003 Colin Bell
05: * colbell@users.sourceforge.net
06: *
07: * This library is free software; you can redistribute it and/or
08: * modify it under the terms of the GNU Lesser General Public
09: * License as published by the Free Software Foundation; either
10: * version 2.1 of the License, or (at your option) any later version.
11: *
12: * This library is distributed in the hope that it will be useful,
13: * but WITHOUT ANY WARRANTY; without even the implied warranty of
14: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15: * Lesser General Public License for more details.
16: *
17: * You should have received a copy of the GNU Lesser General Public
18: * License along with this library; if not, write to the Free Software
19: * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20: */
21: import javax.swing.JTextField;
22: import javax.swing.text.AttributeSet;
23: import javax.swing.text.BadLocationException;
24: import javax.swing.text.Document;
25: import javax.swing.text.PlainDocument;
26:
27: /**
28: * This class is a <CODE>TextField</CODE> that only allows a single
29: * character to be entered into it.
30: *
31: * @author <A HREF="mailto:colbell@users.sourceforge.net">Colin Bell</A>
32: */
33: public class CharField extends JTextField {
34: /**
35: * Default ctor.
36: */
37: public CharField() {
38: super (" ");
39: }
40:
41: /**
42: * Ctor specifying the character
43: */
44: public CharField(char ch) {
45: super ("" + ch);
46: }
47:
48: /**
49: * Retrieve the contents of this field as a <TT>char</TT>. If it
50: * is empty then return a single blank character.
51: *
52: * @return the contents of this field as an <TT>char</TT>.
53: */
54: public char getChar() {
55: final String text = getText();
56: if (text == null || text.length() == 0) {
57: return ' ';
58: }
59: return text.charAt(0);
60: }
61:
62: /**
63: * Set the contents of this field to the passed <TT>char</TT>.
64: *
65: * @param value The new value for this field.
66: */
67: public void setChar(char ch) {
68: setText(String.valueOf(ch));
69: }
70:
71: /**
72: * Create a new document model for this control that only accepts
73: * a single character.
74: *
75: * @return The new document model.
76: */
77: protected Document createDefaultModel() {
78: return new CharacterDocument();
79: }
80:
81: /**
82: * This document only allows a single character to be stored.
83: */
84: static class CharacterDocument extends PlainDocument {
85: public void insertString(int offs, String str, AttributeSet a)
86: throws BadLocationException {
87: if (str != null) {
88: char ch = str.length() > 0 ? str.charAt(0) : ' ';
89: super .remove(0, getLength());
90: super .insertString(0, String.valueOf(ch), a);
91: }
92: }
93: }
94: }
|