import java.awt.*; import java.awt.event.*; import javax.swing.*; //--> Note: Comments starting with //--> are meta-comments about how to write //--> OO Java code and wouldn't appear in a production environment. /** * Class representing a popup login dialog with username * and password. Responsible for collecting user input * and passing it to a SecuritySystem for validation. */ public class PasswordPopup extends JFrame { private final SecuritySystem _securitySystem; // Does security checks private final JTextField _userNameField; // UI field containing username private final JPasswordField _passwordField; // UI field containing password /** Constructor, initializes object with given owner. */ public PasswordPopup(SecuritySystem ss) { //--> Superclass JFrame constructor sets text of title bar from argument: super("Login"); // Keep track of owner: _securitySystem = ss; _userNameField = new JTextField(16); _passwordField = new JPasswordField(16); // Check username/password when user hits enter // key in password field. Use the owner SecuritySystem // for the actual security check. _passwordField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String username = _userNameField.getText(); char[] password = _passwordField.getPassword(); if (!_securitySystem.doLogin(username,password)) { JOptionPane.showMessageDialog(null, "Invalid user name or password. Try again.", "Login Failed", JOptionPane.ERROR_MESSAGE); } } }); // Shut down system when user closes window. this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.out.println("Shutting down security system."); System.exit(0); } } ); //--> The code to initialize the layout of various components //--> is off in its own function just to keep it out of the way. setupLayout(); } private void setupLayout() { JPanel labelPane = new JPanel(); labelPane.setLayout(new GridLayout(0, 1)); labelPane.add(new JLabel("User name:")); labelPane.add(new JLabel("Password:")); // Lay out the text fields in a panel: JPanel fieldPane = new JPanel(); fieldPane.setLayout(new GridLayout(0, 1)); fieldPane.add(_userNameField); fieldPane.add(_passwordField); // Put the panels in another panel, labels on left, // text fields on right: JPanel contentPane = new JPanel(); contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); contentPane.setLayout(new BorderLayout()); contentPane.add(labelPane, BorderLayout.CENTER); contentPane.add(fieldPane, BorderLayout.EAST); //--> The "this." below isn't necessary; it's just there //--> to make it clear where setContentPane and pack live. //--> In most production code the "this." is omitted. this.setContentPane(contentPane); this.pack(); } };