KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > awt > TextField


1 /*
2  * @(#)TextField.java 1.80 04/05/18
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7 package java.awt;
8
9 import java.awt.peer.TextFieldPeer;
10 import java.awt.event.*;
11 import java.util.EventListener JavaDoc;
12 import java.io.ObjectOutputStream JavaDoc;
13 import java.io.ObjectInputStream JavaDoc;
14 import java.io.IOException JavaDoc;
15 import javax.accessibility.*;
16
17
18 /**
19  * A <code>TextField</code> object is a text component
20  * that allows for the editing of a single line of text.
21  * <p>
22  * For example, the following image depicts a frame with four
23  * text fields of varying widths. Two of these text fields
24  * display the predefined text <code>"Hello"</code>.
25  * <p>
26  * <img SRC="doc-files/TextField-1.gif" alt="The preceding text describes this image."
27  * ALIGN=center HSPACE=10 VSPACE=7>
28  * <p>
29  * Here is the code that produces these four text fields:
30  * <p>
31  * <hr><blockquote><pre>
32  * TextField tf1, tf2, tf3, tf4;
33  * // a blank text field
34  * tf1 = new TextField();
35  * // blank field of 20 columns
36  * tf2 = new TextField("", 20);
37  * // predefined text displayed
38  * tf3 = new TextField("Hello!");
39  * // predefined text in 30 columns
40  * tf4 = new TextField("Hello", 30);
41  * </pre></blockquote><hr>
42  * <p>
43  * Every time the user types a key in the text field, one or
44  * more key events are sent to the text field. A <code>KeyEvent</code>
45  * may be one of three types: keyPressed, keyReleased, or keyTyped.
46  * The properties of a key event indicate which of these types
47  * it is, as well as additional information about the event,
48  * such as what modifiers are applied to the key event and the
49  * time at which the event occurred.
50  * <p>
51  * The key event is passed to every <code>KeyListener</code>
52  * or <code>KeyAdapter</code> object which registered to receive such
53  * events using the component's <code>addKeyListener</code> method.
54  * (<code>KeyAdapter</code> objects implement the
55  * <code>KeyListener</code> interface.)
56  * <p>
57  * It is also possible to fire an <code>ActionEvent</code>.
58  * If action events are enabled for the text field, they may
59  * be fired by pressing the <code>Return</code> key.
60  * <p>
61  * The <code>TextField</code> class's <code>processEvent</code>
62  * method examines the action event and passes it along to
63  * <code>processActionEvent</code>. The latter method redirects the
64  * event to any <code>ActionListener</code> objects that have
65  * registered to receive action events generated by this
66  * text field.
67  *
68  * @version 1.80, 05/18/04
69  * @author Sami Shaio
70  * @see java.awt.event.KeyEvent
71  * @see java.awt.event.KeyAdapter
72  * @see java.awt.event.KeyListener
73  * @see java.awt.event.ActionEvent
74  * @see java.awt.Component#addKeyListener
75  * @see java.awt.TextField#processEvent
76  * @see java.awt.TextField#processActionEvent
77  * @see java.awt.TextField#addActionListener
78  * @since JDK1.0
79  */

80 public class TextField extends TextComponent JavaDoc {
81
82     /**
83      * The number of columns in the text field.
84      * A column is an approximate average character
85      * width that is platform-dependent.
86      * Guaranteed to be non-negative.
87      *
88      * @serial
89      * @see #setColumns(int)
90      * @see #getColumns()
91      */

92     int columns;
93
94     /**
95      * The echo character, which is used when
96      * the user wishes to disguise the characters
97      * typed into the text field.
98      * The disguises are removed if echoChar = <code>0</code>.
99      *
100      * @serial
101      * @see #getEchoChar()
102      * @see #setEchoChar(char)
103      * @see #echoCharIsSet()
104      */

105     char echoChar;
106
107     transient ActionListener actionListener;
108
109     private static final String JavaDoc base = "textfield";
110     private static int nameCounter = 0;
111
112     /*
113      * JDK 1.1 serialVersionUID
114      */

115     private static final long serialVersionUID = -2966288784432217853L;
116
117     /**
118      * Initialize JNI field and method ids
119      */

120     private static native void initIDs();
121
122     static {
123         /* ensure that the necessary native libraries are loaded */
124     Toolkit.loadLibraries();
125         if (!GraphicsEnvironment.isHeadless()) {
126             initIDs();
127         }
128     }
129
130     /**
131      * Constructs a new text field.
132      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
133      * returns true.
134      * @see java.awt.GraphicsEnvironment#isHeadless
135      */

136     public TextField() throws HeadlessException JavaDoc {
137     this("", 0);
138     }
139
140     /**
141      * Constructs a new text field initialized with the specified text.
142      * @param text the text to be displayed. If
143      * <code>text</code> is <code>null</code>, the empty
144      * string <code>""</code> will be displayed.
145      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
146      * returns true.
147      * @see java.awt.GraphicsEnvironment#isHeadless
148      */

149     public TextField(String JavaDoc text) throws HeadlessException JavaDoc {
150         this(text, (text != null) ? text.length() : 0);
151     }
152
153     /**
154      * Constructs a new empty text field with the specified number
155      * of columns. A column is an approximate average character
156      * width that is platform-dependent.
157      * @param columns the number of columns. If
158      * <code>columns</code> is less than <code>0</code>,
159      * <code>columns</code> is set to <code>0</code>.
160      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
161      * returns true.
162      * @see java.awt.GraphicsEnvironment#isHeadless
163      */

164     public TextField(int columns) throws HeadlessException JavaDoc {
165     this("", columns);
166     }
167
168     /**
169      * Constructs a new text field initialized with the specified text
170      * to be displayed, and wide enough to hold the specified
171      * number of columns. A column is an approximate average character
172      * width that is platform-dependent.
173      * @param text the text to be displayed. If
174      * <code>text</code> is <code>null</code>, the empty
175      * string <code>""</code> will be displayed.
176      * @param columns the number of columns. If
177      * <code>columns</code> is less than <code>0</code>,
178      * <code>columns</code> is set to <code>0</code>.
179      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
180      * returns true.
181      * @see java.awt.GraphicsEnvironment#isHeadless
182      */

183     public TextField(String JavaDoc text, int columns) throws HeadlessException JavaDoc {
184     super(text);
185         this.columns = (columns >= 0) ? columns : 0;
186     }
187
188     /**
189      * Construct a name for this component. Called by getName() when the
190      * name is null.
191      */

192     String JavaDoc constructComponentName() {
193         synchronized (getClass()) {
194         return base + nameCounter++;
195     }
196     }
197
198     /**
199      * Creates the TextField's peer. The peer allows us to modify the
200      * appearance of the TextField without changing its functionality.
201      */

202     public void addNotify() {
203         synchronized (getTreeLock()) {
204         if (peer == null)
205             peer = getToolkit().createTextField(this);
206         super.addNotify();
207     }
208     }
209
210     /**
211      * Gets the character that is to be used for echoing.
212      * <p>
213      * An echo character is useful for text fields where
214      * user input should not be echoed to the screen, as in
215      * the case of a text field for entering a password.
216      * If <code>echoChar</code> = <code>0</code>, user
217      * input is echoed to the screen unchanged.
218      * @return the echo character for this text field.
219      * @see java.awt.TextField#echoCharIsSet
220      * @see java.awt.TextField#setEchoChar
221      */

222     public char getEchoChar() {
223     return echoChar;
224     }
225
226     /**
227      * Sets the echo character for this text field.
228      * <p>
229      * An echo character is useful for text fields where
230      * user input should not be echoed to the screen, as in
231      * the case of a text field for entering a password.
232      * Setting <code>echoChar</code> = <code>0</code> allows
233      * user input to be echoed to the screen again.
234      * @param c the echo character for this text field.
235      * @see java.awt.TextField#echoCharIsSet
236      * @see java.awt.TextField#getEchoChar
237      * @since JDK1.1
238      */

239     public void setEchoChar(char c) {
240     setEchoCharacter(c);
241     }
242
243     /**
244      * @deprecated As of JDK version 1.1,
245      * replaced by <code>setEchoChar(char)</code>.
246      */

247     @Deprecated JavaDoc
248     public synchronized void setEchoCharacter(char c) {
249         if (echoChar != c) {
250             echoChar = c;
251             TextFieldPeer peer = (TextFieldPeer)this.peer;
252             if (peer != null) {
253                 peer.setEchoCharacter(c);
254             }
255         }
256     }
257
258     /**
259      * Sets the text that is presented by this
260      * text component to be the specified text.
261      * @param t the new text.
262      * @see java.awt.TextComponent#getText
263      */

264     public void setText(String JavaDoc t) {
265         super.setText(t);
266
267     // This could change the preferred size of the Component.
268
if (valid) {
269         invalidate();
270     }
271     }
272
273     /**
274      * Indicates whether or not this text field has a
275      * character set for echoing.
276      * <p>
277      * An echo character is useful for text fields where
278      * user input should not be echoed to the screen, as in
279      * the case of a text field for entering a password.
280      * @return <code>true</code> if this text field has
281      * a character set for echoing;
282      * <code>false</code> otherwise.
283      * @see java.awt.TextField#setEchoChar
284      * @see java.awt.TextField#getEchoChar
285      */

286     public boolean echoCharIsSet() {
287     return echoChar != 0;
288     }
289
290     /**
291      * Gets the number of columns in this text field. A column is an
292      * approximate average character width that is platform-dependent.
293      * @return the number of columns.
294      * @see java.awt.TextField#setColumns
295      * @since JDK1.1
296      */

297     public int getColumns() {
298     return columns;
299     }
300
301     /**
302      * Sets the number of columns in this text field. A column is an
303      * approximate average character width that is platform-dependent.
304      * @param columns the number of columns.
305      * @see java.awt.TextField#getColumns
306      * @exception IllegalArgumentException if the value
307      * supplied for <code>columns</code>
308      * is less than <code>0</code>.
309      * @since JDK1.1
310      */

311     public synchronized void setColumns(int columns) {
312     int oldVal = this.columns;
313     if (columns < 0) {
314         throw new IllegalArgumentException JavaDoc("columns less than zero.");
315     }
316     if (columns != oldVal) {
317         this.columns = columns;
318         invalidate();
319     }
320     }
321
322     /**
323      * Gets the preferred size of this text field
324      * with the specified number of columns.
325      * @param columns the number of columns
326      * in this text field.
327      * @return the preferred dimensions for
328      * displaying this text field.
329      * @since JDK1.1
330      */

331     public Dimension JavaDoc getPreferredSize(int columns) {
332         return preferredSize(columns);
333     }
334
335     /**
336      * @deprecated As of JDK version 1.1,
337      * replaced by <code>getPreferredSize(int)</code>.
338      */

339     @Deprecated JavaDoc
340     public Dimension JavaDoc preferredSize(int columns) {
341         synchronized (getTreeLock()) {
342         TextFieldPeer peer = (TextFieldPeer)this.peer;
343         return (peer != null) ?
344                peer.preferredSize(columns) :
345                super.preferredSize();
346         }
347     }
348
349     /**
350      * Gets the preferred size of this text field.
351      * @return the preferred dimensions for
352      * displaying this text field.
353      * @since JDK1.1
354      */

355     public Dimension JavaDoc getPreferredSize() {
356         return preferredSize();
357     }
358
359     /**
360      * @deprecated As of JDK version 1.1,
361      * replaced by <code>getPreferredSize()</code>.
362      */

363     @Deprecated JavaDoc
364     public Dimension JavaDoc preferredSize() {
365         synchronized (getTreeLock()) {
366         return (columns > 0) ?
367                preferredSize(columns) :
368                super.preferredSize();
369         }
370     }
371
372     /**
373      * Gets the minumum dimensions for a text field with
374      * the specified number of columns.
375      * @param columns the number of columns in
376      * this text field.
377      * @since JDK1.1
378      */

379     public Dimension JavaDoc getMinimumSize(int columns) {
380         return minimumSize(columns);
381     }
382
383     /**
384      * @deprecated As of JDK version 1.1,
385      * replaced by <code>getMinimumSize(int)</code>.
386      */

387     @Deprecated JavaDoc
388     public Dimension JavaDoc minimumSize(int columns) {
389         synchronized (getTreeLock()) {
390         TextFieldPeer peer = (TextFieldPeer)this.peer;
391         return (peer != null) ?
392                peer.minimumSize(columns) :
393                super.minimumSize();
394         }
395     }
396
397     /**
398      * Gets the minumum dimensions for this text field.
399      * @return the minimum dimensions for
400      * displaying this text field.
401      * @since JDK1.1
402      */

403     public Dimension JavaDoc getMinimumSize() {
404         return minimumSize();
405     }
406
407     /**
408      * @deprecated As of JDK version 1.1,
409      * replaced by <code>getMinimumSize()</code>.
410      */

411     @Deprecated JavaDoc
412     public Dimension JavaDoc minimumSize() {
413         synchronized (getTreeLock()) {
414         return (columns > 0) ?
415                minimumSize(columns) :
416                super.minimumSize();
417         }
418     }
419
420     /**
421      * Adds the specified action listener to receive
422      * action events from this text field.
423      * If l is null, no exception is thrown and no action is performed.
424      *
425      * @param l the action listener.
426      * @see #removeActionListener
427      * @see #getActionListeners
428      * @see java.awt.event.ActionListener
429      * @since JDK1.1
430      */

431     public synchronized void addActionListener(ActionListener l) {
432     if (l == null) {
433         return;
434     }
435     actionListener = AWTEventMulticaster.add(actionListener, l);
436         newEventsOnly = true;
437     }
438
439     /**
440      * Removes the specified action listener so that it no longer
441      * receives action events from this text field.
442      * If l is null, no exception is thrown and no action is performed.
443      *
444      * @param l the action listener.
445      * @see #addActionListener
446      * @see #getActionListeners
447      * @see java.awt.event.ActionListener
448      * @since JDK1.1
449      */

450     public synchronized void removeActionListener(ActionListener l) {
451     if (l == null) {
452         return;
453     }
454     actionListener = AWTEventMulticaster.remove(actionListener, l);
455     }
456
457     /**
458      * Returns an array of all the action listeners
459      * registered on this textfield.
460      *
461      * @return all of this textfield's <code>ActionListener</code>s
462      * or an empty array if no action
463      * listeners are currently registered
464      *
465      * @see #addActionListener
466      * @see #removeActionListener
467      * @see java.awt.event#ActionListener
468      * @since 1.4
469      */

470     public synchronized ActionListener[] getActionListeners() {
471         return (ActionListener[])(getListeners(ActionListener.class));
472     }
473
474     /**
475      * Returns an array of all the objects currently registered
476      * as <code><em>Foo</em>Listener</code>s
477      * upon this <code>TextField</code>.
478      * <code><em>Foo</em>Listener</code>s are registered using the
479      * <code>add<em>Foo</em>Listener</code> method.
480      *
481      * <p>
482      * You can specify the <code>listenerType</code> argument
483      * with a class literal, such as
484      * <code><em>Foo</em>Listener.class</code>.
485      * For example, you can query a
486      * <code>TextField</code> <code>t</code>
487      * for its action listeners with the following code:
488      *
489      * <pre>ActionListener[] als = (ActionListener[])(t.getListeners(ActionListener.class));</pre>
490      *
491      * If no such listeners exist, this method returns an empty array.
492      *
493      * @param listenerType the type of listeners requested; this parameter
494      * should specify an interface that descends from
495      * <code>java.util.EventListener</code>
496      * @return an array of all objects registered as
497      * <code><em>Foo</em>Listener</code>s on this textfield,
498      * or an empty array if no such
499      * listeners have been added
500      * @exception ClassCastException if <code>listenerType</code>
501      * doesn't specify a class or interface that implements
502      * <code>java.util.EventListener</code>
503      *
504      * @see #getActionListeners
505      * @since 1.3
506      */

507     public <T extends EventListener JavaDoc> T[] getListeners(Class JavaDoc<T> listenerType) {
508     EventListener JavaDoc l = null;
509     if (listenerType == ActionListener.class) {
510         l = actionListener;
511     } else {
512         return super.getListeners(listenerType);
513     }
514     return AWTEventMulticaster.getListeners(l, listenerType);
515     }
516
517     // REMIND: remove when filtering is done at lower level
518
boolean eventEnabled(AWTEvent JavaDoc e) {
519         if (e.id == ActionEvent.ACTION_PERFORMED) {
520             if ((eventMask & AWTEvent.ACTION_EVENT_MASK) != 0 ||
521                 actionListener != null) {
522                 return true;
523             }
524             return false;
525         }
526         return super.eventEnabled(e);
527     }
528
529     /**
530      * Processes events on this text field. If the event
531      * is an instance of <code>ActionEvent</code>,
532      * it invokes the <code>processActionEvent</code>
533      * method. Otherwise, it invokes <code>processEvent</code>
534      * on the superclass.
535      * <p>Note that if the event parameter is <code>null</code>
536      * the behavior is unspecified and may result in an
537      * exception.
538      *
539      * @param e the event
540      * @see java.awt.event.ActionEvent
541      * @see java.awt.TextField#processActionEvent
542      * @since JDK1.1
543      */

544     protected void processEvent(AWTEvent JavaDoc e) {
545         if (e instanceof ActionEvent) {
546             processActionEvent((ActionEvent)e);
547             return;
548         }
549     super.processEvent(e);
550     }
551
552     /**
553      * Processes action events occurring on this text field by
554      * dispatching them to any registered
555      * <code>ActionListener</code> objects.
556      * <p>
557      * This method is not called unless action events are
558      * enabled for this component. Action events are enabled
559      * when one of the following occurs:
560      * <p><ul>
561      * <li>An <code>ActionListener</code> object is registered
562      * via <code>addActionListener</code>.
563      * <li>Action events are enabled via <code>enableEvents</code>.
564      * </ul>
565      * <p>Note that if the event parameter is <code>null</code>
566      * the behavior is unspecified and may result in an
567      * exception.
568      *
569      * @param e the action event
570      * @see java.awt.event.ActionListener
571      * @see java.awt.TextField#addActionListener
572      * @see java.awt.Component#enableEvents
573      * @since JDK1.1
574      */

575     protected void processActionEvent(ActionEvent e) {
576         ActionListener listener = actionListener;
577         if (listener != null) {
578             listener.actionPerformed(e);
579         }
580     }
581
582     /**
583      * Returns a string representing the state of this <code>TextField</code>.
584      * This method is intended to be used only for debugging purposes, and the
585      * content and format of the returned string may vary between
586      * implementations. The returned string may be empty but may not be
587      * <code>null</code>.
588      *
589      * @return the parameter string of this text field
590      */

591     protected String JavaDoc paramString() {
592     String JavaDoc str = super.paramString();
593     if (echoChar != 0) {
594         str += ",echo=" + echoChar;
595     }
596     return str;
597     }
598
599
600     /*
601      * Serialization support.
602      */

603     /**
604      * The textField Serialized Data Version.
605      *
606      * @serial
607      */

608     private int textFieldSerializedDataVersion = 1;
609
610     /**
611      * Writes default serializable fields to stream. Writes
612      * a list of serializable ActionListener(s) as optional data.
613      * The non-serializable ActionListener(s) are detected and
614      * no attempt is made to serialize them.
615      *
616      * @serialData Null terminated sequence of zero or more pairs.
617      * A pair consists of a String and Object.
618      * The String indicates the type of object and
619      * is one of the following :
620      * ActionListenerK indicating and ActionListener object.
621      *
622      * @see AWTEventMulticaster#save(ObjectOutputStream, String, EventListener)
623      * @see java.awt.Component#actionListenerK
624      */

625     private void writeObject(ObjectOutputStream JavaDoc s)
626       throws IOException JavaDoc
627     {
628         s.defaultWriteObject();
629
630         AWTEventMulticaster.save(s, actionListenerK, actionListener);
631         s.writeObject(null);
632     }
633
634     /**
635      * Read the ObjectInputStream and if it isn't null,
636      * add a listener to receive action events fired by the
637      * TextField. Unrecognized keys or values will be
638      * ignored.
639      *
640      * @exception HeadlessException if
641      * <code>GraphicsEnvironment.isHeadless()</code> returns
642      * <code>true</code>
643      * @see #removeActionListener(ActionListener)
644      * @see #addActionListener(ActionListener)
645      * @see java.awt.GraphicsEnvironment#isHeadless
646      */

647     private void readObject(ObjectInputStream JavaDoc s)
648       throws ClassNotFoundException JavaDoc, IOException JavaDoc, HeadlessException JavaDoc
649     {
650         // HeadlessException will be thrown by TextComponent's readObject
651
s.defaultReadObject();
652
653         // Make sure the state we just read in for columns has legal values
654
if (columns < 0) {
655             columns = 0;
656         }
657
658         // Read in listeners, if any
659
Object JavaDoc keyOrNull;
660         while(null != (keyOrNull = s.readObject())) {
661         String JavaDoc key = ((String JavaDoc)keyOrNull).intern();
662
663         if (actionListenerK == key) {
664                 addActionListener((ActionListener)(s.readObject()));
665             } else {
666                 // skip value for unrecognized key
667
s.readObject();
668             }
669         }
670     }
671
672
673 /////////////////
674
// Accessibility support
675
////////////////
676

677
678     /**
679      * Gets the AccessibleContext associated with this TextField.
680      * For text fields, the AccessibleContext takes the form of an
681      * AccessibleAWTTextField.
682      * A new AccessibleAWTTextField instance is created if necessary.
683      *
684      * @return an AccessibleAWTTextField that serves as the
685      * AccessibleContext of this TextField
686      */

687     public AccessibleContext getAccessibleContext() {
688         if (accessibleContext == null) {
689             accessibleContext = new AccessibleAWTTextField();
690         }
691         return accessibleContext;
692     }
693
694     /**
695      * This class implements accessibility support for the
696      * <code>TextField</code> class. It provides an implementation of the
697      * Java Accessibility API appropriate to text field user-interface elements.
698      */

699     protected class AccessibleAWTTextField extends AccessibleAWTTextComponent
700     {
701         /*
702          * JDK 1.3 serialVersionUID
703          */

704         private static final long serialVersionUID = 6219164359235943158L;
705
706         /**
707          * Gets the state set of this object.
708          *
709          * @return an instance of AccessibleStateSet describing the states
710          * of the object
711          * @see AccessibleState
712          */

713         public AccessibleStateSet getAccessibleStateSet() {
714             AccessibleStateSet states = super.getAccessibleStateSet();
715             states.add(AccessibleState.SINGLE_LINE);
716             return states;
717         }
718     }
719
720 }
721
Popular Tags