Friday, September 2, 2011

Java JPasswordField class

Java Swing Tutorial Explaining the JPasswordField Component. JPasswordField (a direct subclass of JTextField) you can suppress the display of input. Each character entered can be replaced by an echo character. This allows confidential input for passwords, for example. By default, the echo character is the asterisk, *. When the user types data into them and presses the Enter key, an action event occurs. If the program registers an event listener, the listener processes the event and can use the data in the text field at the time of the event in the program. If you need to provide an editable text field that doesn’t show the characters the user types – use the JPasswordField class.

JPasswordField Source Code

public class JPasswordFieldDemo {

	public static void main(String[] argv) {
		final JFrame frame = new JFrame("JPassword Usage Demo");
		JLabel jlbPassword = new JLabel("Enter the password: ");
		JPasswordField jpwName = new JPasswordField(10);
		jpwName.setEchoChar('*');
		jpwName.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				JPasswordField input = (JPasswordField) e.getSource();
                                	char[] password = input.getPassword();
				if (isPasswordCorrect(password)) {
					JOptionPane.showMessageDialog(frame,
							"Correct  password.");
				} else {
					JOptionPane.showMessageDialog(frame,
							"Sorry. Try again.", "Error Message",
							JOptionPane.ERROR_MESSAGE);
				}
			}
		});
		JPanel jplContentPane = new JPanel(new BorderLayout());
		jplContentPane.setBorder(BorderFactory.createEmptyBorder(20, 20,
				20, 20));
		jplContentPane.add(jlbPassword, BorderLayout.WEST);
		jplContentPane.add(jpwName, BorderLayout.CENTER);
		frame.setContentPane(jplContentPane);
		frame.addWindowListener(new WindowAdapter() {

			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
		frame.pack();
		frame.setVisible(true);
	}
	private static boolean isPasswordCorrect(char[] inputPassword) {
		char[] actualPassword = { 'h', 'e', 'm', 'a', 'n', 't', 'h' };
		if (inputPassword.length != actualPassword.length)
			return false; // Return false if lengths are unequal
		for (int i = 0; i < inputPassword.length; i++)
			if (inputPassword[i] != actualPassword[i])
				return false;
		return true;
	}
}




Output


 

 




No comments:

Post a Comment