[Java Swing] JPasswordField in Java – JPasswordField in Java

Content
Create JPasswordField
Getting the facts and get the password from JPasswordField

JPasswordField the object allows us to enter a line of text like JTextField but is hidden by asterisks (*) or dots to create a password (password). JPasswordField often used together to create a pair JTextField User name and password as shown below:

JPasswordField in Java swing

Now we'll go through the construction JPasswordField program as above.

Create JPasswordField

We have a number of methods commonly used to initialize JPasswordField:
– JPasswordField(): Initialize JPasswordField no text and the width is 0 post
– JPasswordField(int columns): Initialize JPasswordField no text columns and column widths are
– JPasswordField(String text): Initialize the original text Voit JPasswordField
– JPasswordField(String text, int columns): Initialize JPasswordField Voit original text columns and column width

First we will create the interface of the program. The interface consists of 1 JPanel là main panel đặt BorderLayout contains InputPanel and ButtonPanel. InputPanel put a JPanel GridLayout contain 2 JLabel, 1 JTextField nhập user name, 1 JPasswordField enter password. ButtonPanel contain 2 JButton is btnLogin and btnHelp.

package nguyenvanquan7826.JPasswordField;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

public class MyJPasswordField extends JFrame implements ActionListener {
	private JTextField tfUserName;
	private JPasswordField pf;
	private JButton btnLogin, btnHelp;

	public MyJPasswordField() {
		// add main panel to frame
		add(createMainPanel());

		// set display
		setTitle("JPasswordField");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		pack();
		setLocationRelativeTo(null);
		setVisible(true);
	}

	// create main panel containes input panel and button panel
	private JPanel createMainPanel() {
		JPanel panel = new JPanel(new BorderLayout());
		panel.setBorder(new EmptyBorder(10, 10, 10, 10));
		panel.add(createInputPanel(), BorderLayout.CENTER);
		panel.add(createButtonPanel(), BorderLayout.PAGE_END);
		return panel;
	}

	// create input panel
	private JPanel createInputPanel() {
		int col = 15; // column of JTextField and JPasswordField
		JPanel panel = new JPanel(new GridLayout(2, 2, 5, 5));
		panel.add(createLabel("User name:"));
		panel.add(tfUserName = createTextField(col));
		panel.add(createLabel("Password:"));
		panel.add(pf = createPasswordField(col));
		return panel;
	}

	// create button panel with button login and button help
	private JPanel createButtonPanel() {
		JPanel panel = new JPanel();
		panel.add(btnLogin = createButton("Login"));
		panel.add(btnHelp = createButton("Help"));
		return panel;
	}

	// create a JLabel with text
	private JLabel createLabel(String text) {
		JLabel lb = new JLabel(text);
		return lb;
	}

	// create JTextField with column is col
	private JTextField createTextField(int col) {
		JTextField tf = new JTextField(col);
		return tf;
	}

	// create JPasswordField with column is col
	private JPasswordField createPasswordField(int col) {
		JPasswordField pf = new JPasswordField(col);
		return pf;
	}

	// create JButton with text is btnName and add ActionListener
	private JButton createButton(String btnName) {
		JButton btn = new JButton(btnName);
		btn.addActionListener(this);
		return btn;
	}

	@Override
	public void actionPerformed(ActionEvent e) {

	}

	public static void main(String[] args) {
		new MyJPasswordField();
	}
}

Our next task is to create and capture events for user name and password and compared with the original data to show the message log success or failure.

Getting the facts and get the password from JPasswordField

To capture the events of JPasswordField similar to JButton, we need to perform addActionListener for it. And another point is that it is often setActionCommand it's similar to ActionCommand btnLogin to enter the password when finished and press Enter, you can make the process even without laborious click btnLogin. Using methods getPassword() to retrieve the password in JPasswordField. This method returns an array of characters as the characters in the password string. We can use the method getText() but it is recommended not to use more.

We need to update the method createPasswordField and createButton as follows:

// create JPasswordField with column is col
private JPasswordField createPasswordField(String action, int col) {
	JPasswordField pf = new JPasswordField(col);
	// set actionCommand for JPasswordField
	pf.setActionCommand(action);
	// add action for JPasswordField
	pf.addActionListener(this);
	return pf;
}

// create JButton with text is btnName and add ActionListener
private JButton createButton(String action, String btnName) {
	JButton btn = new JButton(btnName);
	btn.setActionCommand(action);
	btn.addActionListener(this);
	return btn;
}

Finally, the remaining data processing only. Note to display a message that we used JOptionPane to display a notification dialog.

JPasswordField in Java swing

Complete the following code

package nguyenvanquan7826.JPasswordField;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

public class MyJPasswordField extends JFrame implements ActionListener {
	private JTextField tfUserName;
	private JPasswordField pf;
	private JButton btnLogin, btnHelp;
	String actionLogin = "login";
	String actionHelp = "help";

	public MyJPasswordField() {
		// add main panel to frame
		add(createMainPanel());

		// set display
		setTitle("JPasswordField");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		pack();
		setLocationRelativeTo(null);
		setVisible(true);
	}

	// create main panel containes input panel and button panel
	private JPanel createMainPanel() {
		JPanel panel = new JPanel(new BorderLayout());
		panel.setBorder(new EmptyBorder(10, 10, 10, 10));
		panel.add(createInputPanel(), BorderLayout.CENTER);
		panel.add(createButtonPanel(), BorderLayout.PAGE_END);
		return panel;
	}

	// create input panel
	private JPanel createInputPanel() {
		int col = 15; // column of JTextField and JPasswordField
		JPanel panel = new JPanel(new GridLayout(2, 2, 5, 5));
		panel.add(createLabel("User name:"));
		panel.add(tfUserName = createTextField(col));
		panel.add(createLabel("Password:"));
		panel.add(pf = createPasswordField(actionLogin, col));
		return panel;
	}

	// create button panel with button login and button help
	private JPanel createButtonPanel() {
		JPanel panel = new JPanel();
		panel.add(btnLogin = createButton(actionLogin, "Login"));
		panel.add(btnHelp = createButton(actionHelp, "Help"));
		return panel;
	}

	// create a JLabel with text
	private JLabel createLabel(String text) {
		JLabel lb = new JLabel(text);
		return lb;
	}

	// create JTextField with column is col
	private JTextField createTextField(int col) {
		JTextField tf = new JTextField(col);
		return tf;
	}

	// create JPasswordField with column is col
	private JPasswordField createPasswordField(String action, int col) {
		JPasswordField pf = new JPasswordField(col);
		// set actionCommand for JPasswordField
		pf.setActionCommand(action);
		// add action for JPasswordField
		pf.addActionListener(this);
		return pf;
	}

	// create JButton with text is btnName and add ActionListener
	private JButton createButton(String action, String btnName) {
		JButton btn = new JButton(btnName);
		btn.setActionCommand(action);
		btn.addActionListener(this);
		return btn;
	}

	// check password
	private boolean checkData(String inputUserName, char[] inputPassword) {
		String userName = "nguyenvanquan";
		char[] password = { '7', '8', '2', '6' };
		return (Arrays.equals(inputPassword, password) && userName
				.equals(inputUserName));
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String command = e.getActionCommand();

		// enter on JPasswordField or click button Login to Login
		if (actionLogin.equals(command)) {
			if (checkData(tfUserName.getText(), pf.getPassword())) {
				JOptionPane.showMessageDialog(null, "login success!", "login",
						JOptionPane.INFORMATION_MESSAGE);
			} else {
				JOptionPane.showMessageDialog(null, "login failed, Try again!",
						"login", JOptionPane.ERROR_MESSAGE);
			}
			return;
		}
		// click button help
		if (actionHelp.equals(command)) {
			JOptionPane.showMessageDialog(null, "get user name and password in"
					+ "n" + "cachhoc.net", "help",
					JOptionPane.INFORMATION_MESSAGE);
			return;
		}
	}

	public static void main(String[] args) {
		new MyJPasswordField();
	}
}

Read more: class JPasswordField, use JPasswordField