KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > javax > swing > JPasswordField


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

7 package javax.swing;
8
9 import javax.swing.text.*;
10 import javax.swing.plaf.*;
11 import javax.accessibility.*;
12
13 import java.io.ObjectOutputStream JavaDoc;
14 import java.io.ObjectInputStream JavaDoc;
15 import java.io.IOException JavaDoc;
16
17 /**
18  * <code>JPasswordField</code> is a lightweight component that allows
19  * the editing of a single line of text where the view indicates
20  * something was typed, but does not show the original characters.
21  * You can find further information and examples in
22  * <a HREF="http://java.sun.com/docs/books/tutorial/uiswing/components/textfield.html">How to Use Text Fields</a>,
23  * a section in <em>The Java Tutorial.</em>
24  * <p>
25  * <code>JPasswordField</code> is intended
26  * to be source-compatible with <code>java.awt.TextField</code>
27  * used with <code>echoChar</code> set. It is provided separately
28  * to make it easier to safely change the UI for the
29  * <code>JTextField</code> without affecting password entries.
30  * <p>
31  * <strong>Warning:</strong>
32  * Serialized objects of this class will not be compatible with
33  * future Swing releases. The current serialization support is
34  * appropriate for short term storage or RMI between applications running
35  * the same version of Swing. As of 1.4, support for long term storage
36  * of all JavaBeans<sup><font size="-2">TM</font></sup>
37  * has been added to the <code>java.beans</code> package.
38  * Please see {@link java.beans.XMLEncoder}.
39  *
40  * @beaninfo
41  * attribute: isContainer false
42  * description: Allows the editing of a line of text but doesn't show the characters.
43  *
44  * @author Timothy Prinzing
45  * @version 1.54 06/02/04
46  */

47 public class JPasswordField extends JTextField JavaDoc {
48
49     /**
50      * Constructs a new <code>JPasswordField</code>,
51      * with a default document, <code>null</code> starting
52      * text string, and 0 column width.
53      */

54     public JPasswordField() {
55         this(null,null,0);
56     }
57
58     /**
59      * Constructs a new <code>JPasswordField</code> initialized
60      * with the specified text. The document model is set to the
61      * default, and the number of columns to 0.
62      *
63      * @param text the text to be displayed, <code>null</code> if none
64      */

65     public JPasswordField(String JavaDoc text) {
66         this(null, text, 0);
67     }
68
69     /**
70      * Constructs a new empty <code>JPasswordField</code> with the specified
71      * number of columns. A default model is created, and the initial string
72      * is set to <code>null</code>.
73      *
74      * @param columns the number of columns >= 0
75      */

76     public JPasswordField(int columns) {
77         this(null, null, columns);
78     }
79
80     /**
81      * Constructs a new <code>JPasswordField</code> initialized with
82      * the specified text and columns. The document model is set to
83      * the default.
84      *
85      * @param text the text to be displayed, <code>null</code> if none
86      * @param columns the number of columns >= 0
87      */

88     public JPasswordField(String JavaDoc text, int columns) {
89         this(null, text, columns);
90     }
91
92     /**
93      * Constructs a new <code>JPasswordField</code> that uses the
94      * given text storage model and the given number of columns.
95      * This is the constructor through which the other constructors feed.
96      * The echo character is set to '*'. If the document model is
97      * <code>null</code>, a default one will be created.
98      *
99      * @param doc the text storage to use
100      * @param txt the text to be displayed, <code>null</code> if none
101      * @param columns the number of columns to use to calculate
102      * the preferred width >= 0; if columns is set to zero, the
103      * preferred width will be whatever naturally results from
104      * the component implementation
105      */

106     public JPasswordField(Document doc, String JavaDoc txt, int columns) {
107         super(doc, txt, columns);
108         echoChar = '*';
109         // We could either leave this on, which wouldn't be secure,
110
// or obscure the composted text, which essentially makes displaying
111
// it useless. Therefore, we turn off input methods.
112
enableInputMethods(false);
113     }
114
115     /**
116      * Returns the name of the L&F class that renders this component.
117      *
118      * @return the string "PasswordFieldUI"
119      * @see JComponent#getUIClassID
120      * @see UIDefaults#getUI
121      */

122     public String JavaDoc getUIClassID() {
123         return uiClassID;
124     }
125
126
127     /**
128      * Returns the character to be used for echoing. The default is '*'.
129      *
130      * @return the echo character, 0 if unset
131      * @see #setEchoChar
132      * @see #echoCharIsSet
133      */

134     public char getEchoChar() {
135         return echoChar;
136     }
137
138     /**
139      * Sets the echo character for this <code>JPasswordField</code>.
140      * Note that this is largely a suggestion, since the
141      * view that gets installed can use whatever graphic techniques
142      * it desires to represent the field. Setting a value of 0 indicates
143      * that you wish to see the text as it is typed, similar to
144      * the behavior of a standard <code>JTextField</code>.
145      *
146      * @param c the echo character to display
147      * @see #echoCharIsSet
148      * @see #getEchoChar
149      * @beaninfo
150      * description: character to display in place of the real characters
151      * attribute: visualUpdate true
152      */

153     public void setEchoChar(char c) {
154         echoChar = c;
155         repaint();
156         revalidate();
157     }
158
159     /**
160      * Returns true if this <code>JPasswordField</code> has a character
161      * set for echoing. A character is considered to be set if the echo
162      * character is not 0.
163      *
164      * @return true if a character is set for echoing
165      * @see #setEchoChar
166      * @see #getEchoChar
167      */

168     public boolean echoCharIsSet() {
169         return echoChar != 0;
170     }
171
172     // --- JTextComponent methods ----------------------------------
173

174     /**
175      * Invokes <code>provideErrorFeedback</code> on the current
176      * look and feel, which typically initiates an error beep.
177      * The normal behavior of transferring the
178      * currently selected range in the associated text model
179      * to the system clipboard, and removing the contents from
180      * the model, is not acceptable for a password field.
181      */

182     public void cut() {
183         if (getClientProperty("JPasswordField.cutCopyAllowed") != Boolean.TRUE) {
184             UIManager.getLookAndFeel().provideErrorFeedback(this);
185         } else {
186             super.cut();
187         }
188     }
189
190     /**
191      * Invokes <code>provideErrorFeedback</code> on the current
192      * look and feel, which typically initiates an error beep.
193      * The normal behavior of transferring the
194      * currently selected range in the associated text model
195      * to the system clipboard, and leaving the contents from
196      * the model, is not acceptable for a password field.
197      */

198     public void copy() {
199         if (getClientProperty("JPasswordField.cutCopyAllowed") != Boolean.TRUE) {
200             UIManager.getLookAndFeel().provideErrorFeedback(this);
201         } else {
202             super.copy();
203         }
204     }
205
206     /**
207      * Returns the text contained in this <code>TextComponent</code>.
208      * If the underlying document is <code>null</code>, will give a
209      * <code>NullPointerException</code>.
210      * <p>
211      * For security reasons, this method is deprecated. Use the
212      <code>* getPassword</code> method instead.
213      * @deprecated As of Java 2 platform v1.2,
214      * replaced by <code>getPassword</code>.
215      * @return the text
216      */

217     @Deprecated JavaDoc
218     public String JavaDoc getText() {
219     return super.getText();
220     }
221
222     /**
223      * Fetches a portion of the text represented by the
224      * component. Returns an empty string if length is 0.
225      * <p>
226      * For security reasons, this method is deprecated. Use the
227      * <code>getPassword</code> method instead.
228      * @deprecated As of Java 2 platform v1.2,
229      * replaced by <code>getPassword</code>.
230      * @param offs the offset >= 0
231      * @param len the length >= 0
232      * @return the text
233      * @exception BadLocationException if the offset or length are invalid
234      */

235     @Deprecated JavaDoc
236     public String JavaDoc getText(int offs, int len) throws BadLocationException {
237         return super.getText(offs, len);
238     }
239
240     /**
241      * Returns the text contained in this <code>TextComponent</code>.
242      * If the underlying document is <code>null</code>, will give a
243      * <code>NullPointerException</code>. For stronger
244      * security, it is recommended that the returned character array be
245      * cleared after use by setting each character to zero.
246      *
247      * @return the text
248      */

249     public char[] getPassword() {
250         Document doc = getDocument();
251     Segment txt = new Segment();
252         try {
253             doc.getText(0, doc.getLength(), txt); // use the non-String API
254
} catch (BadLocationException e) {
255         return null;
256         }
257     char[] retValue = new char[txt.count];
258     System.arraycopy(txt.array, txt.offset, retValue, 0, txt.count);
259         return retValue;
260     }
261
262     /**
263      * See readObject() and writeObject() in JComponent for more
264      * information about serialization in Swing.
265      */

266     private void writeObject(ObjectOutputStream JavaDoc s) throws IOException JavaDoc {
267         s.defaultWriteObject();
268         if (getUIClassID().equals(uiClassID)) {
269             byte count = JComponent.getWriteObjCounter(this);
270             JComponent.setWriteObjCounter(this, --count);
271             if (count == 0 && ui != null) {
272                 ui.installUI(this);
273             }
274         }
275     }
276
277     // --- variables -----------------------------------------------
278

279     /**
280      * @see #getUIClassID
281      * @see #readObject
282      */

283     private static final String JavaDoc uiClassID = "PasswordFieldUI";
284
285     private char echoChar;
286
287
288     /**
289      * Returns a string representation of this <code>JPasswordField</code>.
290      * This method is intended to be used only for debugging purposes, and the
291      * content and format of the returned string may vary between
292      * implementations. The returned string may be empty but may not
293      * be <code>null</code>.
294      *
295      * @return a string representation of this <code>JPasswordField</code>
296      */

297     protected String JavaDoc paramString() {
298     return super.paramString() +
299     ",echoChar=" + echoChar;
300     }
301
302 /////////////////
303
// Accessibility support
304
////////////////
305

306
307     /**
308      * Returns the <code>AccessibleContext</code> associated with this
309      * <code>JPasswordField</code>. For password fields, the
310      * <code>AccessibleContext</code> takes the form of an
311      * <code>AccessibleJPasswordField</code>.
312      * A new <code>AccessibleJPasswordField</code> instance is created
313      * if necessary.
314      *
315      * @return an <code>AccessibleJPasswordField</code> that serves as the
316      * <code>AccessibleContext</code> of this
317      * <code>JPasswordField</code>
318      */

319     public AccessibleContext getAccessibleContext() {
320         if (accessibleContext == null) {
321             accessibleContext = new AccessibleJPasswordField();
322         }
323         return accessibleContext;
324     }
325
326     /**
327      * This class implements accessibility support for the
328      * <code>JPasswordField</code> class. It provides an implementation of the
329      * Java Accessibility API appropriate to password field user-interface
330      * elements.
331      * <p>
332      * <strong>Warning:</strong>
333      * Serialized objects of this class will not be compatible with
334      * future Swing releases. The current serialization support is
335      * appropriate for short term storage or RMI between applications running
336      * the same version of Swing. As of 1.4, support for long term storage
337      * of all JavaBeans<sup><font size="-2">TM</font></sup>
338      * has been added to the <code>java.beans</code> package.
339      * Please see {@link java.beans.XMLEncoder}.
340      */

341     protected class AccessibleJPasswordField extends AccessibleJTextField {
342
343         /**
344          * Gets the role of this object.
345          *
346          * @return an instance of AccessibleRole describing the role of the
347          * object (AccessibleRole.PASSWORD_TEXT)
348          * @see AccessibleRole
349          */

350         public AccessibleRole getAccessibleRole() {
351             return AccessibleRole.PASSWORD_TEXT;
352         }
353     }
354 }
355
Popular Tags