From 13d0a13392071df08b1e90ca0ee7b9e72afd2a86 Mon Sep 17 00:00:00 2001 From: Richard Schmidt Date: Wed, 7 Feb 2024 14:57:22 +0100 Subject: [PATCH] Made it so pressing enter on the keyboard activates the login and ok button --- src/main/java/LoginGUI.java | 37 +++++++++++++++++++++++++++++-------- 1 file changed, 29 insertions(+), 8 deletions(-) diff --git a/src/main/java/LoginGUI.java b/src/main/java/LoginGUI.java index d19db0e..e18d2ea 100644 --- a/src/main/java/LoginGUI.java +++ b/src/main/java/LoginGUI.java @@ -2,6 +2,8 @@ import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.List; +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; public class LoginGUI extends JFrame implements ActionListener { private JTextField usernameField; @@ -35,22 +37,26 @@ public class LoginGUI extends JFrame implements ActionListener { loginButton.addActionListener(this); add(loginButton); + getRootPane().setDefaultButton(loginButton); + } @Override public void actionPerformed(ActionEvent e) { - if (e.getSource() == loginButton) { - String username = usernameField.getText(); - String password = new String(passwordField.getPassword()); + if (e.getSource() == loginButton) { + login(); + } + } - if (authenticateUser(username, password)) { + private void login() { + String username = usernameField.getText(); + String password = new String(passwordField.getPassword()); + + if (authenticateUser(username, password)) { JOptionPane.showMessageDialog(this, "Login successful!"); // Perform actions after successful login - } else { + } else { JOptionPane.showMessageDialog(this, "Invalid username or password", "Login Error", JOptionPane.ERROR_MESSAGE); - } - - } } @@ -68,6 +74,21 @@ public class LoginGUI extends JFrame implements ActionListener { } + private class EnterKeyListener implements KeyListener { + @Override + public void keyTyped(KeyEvent e) {} + + @Override + public void keyPressed(KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_ENTER) { + login(); + } + } + + @Override + public void keyReleased(KeyEvent e) {} + } + public static void main(String[] args) { SwingUtilities.invokeLater(() -> { LoginGUI loginGUI = new LoginGUI();