1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
|
import javax.swing.*; import java.awt.event.*; import java.awt.*;
public class Password extends JFrame implements ActionListener { //TestJPF JPasswordField jpf; String pwd = "cae4"; int count; JTextField jtf;
public Password () { count = 0;
jtf = new JTextField(15); jtf.setEditable(false);
// A JPasswordField object is created. The echo character is // set to '$' and the JPasswordField object is registered with // an ActionListener.
jpf = new JPasswordField(20); jpf.setEchoChar('$'); jpf.addActionListener(this);
JPanel p = new JPanel(); p.setLayout(new FlowLayout(FlowLayout.CENTER, 20, 20)); p.add(jpf);
getContentPane().add(p, BorderLayout.CENTER); getContentPane().add(jtf, BorderLayout.SOUTH);
// The WindowListener is used to terminate the program when the window // is closed. Under Java 2 version 1.3, the addWindowListener() syntax // can be replaced by // // setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addWindowListener(new WinClosing()); setBounds(100, 100, 300, 150); setVisible(true); }
// When the JPasswordField has focus and the enter key is pressed, // an ActionEvent is generated and the actionPerformed() method is // called. The entered text is compared against the password. // After 3 unsuccessful tries, the program terminates.
public void actionPerformed(ActionEvent ae) { String enteredPwd = new String(jpf.getPassword());
if (pwd.equals(enteredPwd)) { jtf.setText("Password accepted"); } else { if (count > 2) { System.exit(0); }
jtf.setText("Wrong Password"); ++count; } }
public static void main(String args[]) { Password tjp = new Password (); } }
// The WinClosing class terminates the program when the window is closed
class WinClosing extends WindowAdapter { public void windowClosing(WindowEvent we) { System.exit(0); } } |