JTextField JPasswordField Example Java

JTextField JPasswordField Example Java


JPasswordField text is implicitly encrypted which takes extra code in AWT TextField.

JTextField and JPasswordField are used to take keyboard input from the user or a programmer can display some text (message) to the user. The limitation of JTextField component is it displays a single line of editable text, using a single font and a single color. Horizontal alignment of either LEFT, CENTER OR RIGHT can be specified for the text in JTextField (unlike TextField of AWT) .

A text field's preferred width (or size) can be set by specifying the number of columns(but, ultimate deciding authority is Layout manager, which you learnt in AWT).

Swing package contains JPasswordField (does not exist in AWT) class which displays each letter typed as '*' by default. The asterisk is called as an echo character which can be changed to the user's choice as in the following JPasswordField code.

JPasswordField

jfield = new JTextField();
jfield.setColumns(30);
jfield.setText(“This is JTextField”);

In the above code, 30 gives the size of the text field; that is, at a time we can see 30 characters and the extra characters entered by the user can be seen using arrow keys. The above three statements can be replaced with a single statement as follows.

jfield = new JTextField(“This is JTextField”, 30);

Unlike in Java AWT TextField, the text in the JTextField can be aligned. In the following statement, the text is right aligned.

jfield.setHorizontalAlignment(JTextField.RIGHT);

The default echo character in JPasswordField is ' * ' and can be changed to any other character using setEchoChar(char) method.

pfield.setEchoChar(‘@’);

In the above statement, whatever is typed in pfield is echoed as @. It is to protect the password from reading by others.

On JTextField and JPasswordField two programs exist:

Leave a Reply

Your email address will not be published. Required fields are marked *