how to create jpasswordfield in java with detail example

-JPasswordField in java is an object that allows us to enter a text line like JTextField but hidden by an asterisk (*) or dot to create a password. JPasswordField in java is commonly used with JTextField to create the User name and password pairs as shown below:
jpasswordfield-in-java-example
-Now we will discover JPasswordField in java through building a program as above.

Create JPasswordField in java

We have some commonly used JPasswordField in java initialization methods:

- JPasswordField (): The JPasswordField initialization has no text and the width is 0 columns.
- JPasswordField (int columns): The JPasswordField initialization has no text and the width is column.
- JPasswordField (String text): Initializes JPasswordField with original text
- JPasswordField (String text, int columns): Initialize JPasswordField with original text and column width ..

-We will first create the interface of the program. The interface consists of one JPanel, the main panel that places the BorderLayout containing the InputPanel and the ButtonPanel. InputPanel is a JPanel that puts a GridLayout containing two JLabels, one JTextField, a user name, and a JPasswordField to enter a password. The ButtonPanel contains two JButton btnLogin and btnHelp.

-File name: MyJPasswordField.java
jpasswordfield-in-java-example
-Continue MyJPasswordField.java
jpasswordfield-in-java-example
-Continue MyJPasswordField.java
jpasswordfield-in-java-example
-Our next task is to create and capture events to obtain user names and passwords and compare them with the original data to display successful or failed login messages.

Getting events and getting passwords from JPasswordField in java

-To catch the JPasswordField in java event similar to JButton, we need to implement the addActionListener for it. And one more point is that we often setActionCommand to it similar to btnLogin's ActionCommand so that after entering the password and press Enter can execute the process immediately without spending time clicking btnLogin. Use the getPassword () method to get the password in JPasswordField in java . This method returns an array of characters that are characters in the password string. You can use the getText () method, but it is recommended that you do not use it.

-We need to modify the createPasswordField and createButton methods as follows:
jpasswordfield-in-java-example
-Finally, the rest is data processing only. Note to display the message we use JOptionPane to display the notification dialog.
jpasswordfield-in-java-example
-The complete code is as follows:
-File name MyJPasswordField.java
jpasswordfield-in-java-example
-Continue MyJPasswordField.java
jpasswordfield-in-java-example
-Continue MyJPasswordField.java
jpasswordfield-in-java-example
-Continue MyJPasswordField.java
jpasswordfield-in-java-example
-Read more JPanel GridLayout java example:

Comments