import javax.swing.JPasswordField; import javax.swing.JFrame; import javax.swing.JLabel; import java.awt.Component; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; /* Author: James Tam Version: March 29, 2021 */ public class MyFrame extends JFrame implements ActionListener { private static final String THE_PASSWORD = "123456"; private JPasswordField aPasswordField; public MyFrame() { JLabel aLabel = new JLabel("Enter password"); aPasswordField = new JPasswordField(); aPasswordField.addActionListener(this); aPasswordField.setBounds(50,70,100,20); aLabel.setBounds(50,50,100,20); setLayout(null); add(aPasswordField); add(aLabel); setBounds(100,100,400,300); setVisible(true); } public void actionPerformed(ActionEvent e) { final int MATCH = 0; Component aComponent = (Component) e.getSource(); if (aComponent instanceof JPasswordField) { JPasswordField aPasswordField = (JPasswordField) aComponent; String passWordEntered = new String(aPasswordField.getPassword()); if (passWordEntered.compareTo(THE_PASSWORD) == MATCH) { System.out.println("Match"); loginSuccess(); } else { System.out.println("Wrong"); loginFailed(); } } } public void loginFailed() { final int DELAY = 3000; setTitle("Password incorrect"); try { Thread.sleep(DELAY); } catch (InterruptedException ex) { System.out.println("Pausing of program was interrupted"); } setTitle(""); } public void loginSuccess() { final int DELAY = 3000; setTitle("Login successful! Your reward is coming."); try { Thread.sleep(DELAY); } catch (InterruptedException ex) { System.out.println("Pausing of program was interrupted"); } setVisible(false); dispose(); } }