Implement a login validation system using file handling in JavaFX

  1. Create a text file called “users.txt” and store the login credentials in the following format:

username1 password1 ,username2 password2, username3 password3

Create a JavaFX class called “LoginValidation” and define the following method:

public static boolean validateLogin(String username, String password) {
   try {
       File file = new File("users.txt");
       Scanner scanner = new Scanner(file);
       while (scanner.hasNextLine()) {
           String line = scanner.nextLine();
           String[] tokens = line.split(" ");
           if (tokens[0].equals(username) && tokens[1].equals(password)) {
               return true;
           }
       }
       scanner.close();
   } catch (FileNotFoundException e) {
       e.printStackTrace();
   }
   return false;
}

In your JavaFX controller class, create a method that handles the login button’s click event and calls the “validateLogin” method. If the login is successful, show a message saying “Login successful!”, and if it fails, show a message saying “Invalid username or password.”

ow you could use the “validateLogin” method in a JavaFX controller class:

import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;

public class LoginController {
   @FXML
   private TextField usernameField;
   @FXML
   private PasswordField passwordField;

   @FXML
   private void handleLoginButtonAction() {
       String username = usernameField.getText();
       String password = passwordField.getText();
       if (LoginValidation.validateLogin(username, password)) {
           Alert alert = new Alert(Alert.AlertType.INFORMATION);
           alert.setTitle("Login Successful");
           alert.setHeaderText(null);
           alert.setContentText("Login successful!");
           alert.showAndWait();
       } else {
           Alert alert = new Alert(Alert.AlertType.ERROR);
           alert.setTitle("Invalid Login");
           alert.setHeaderText(null);
           alert.setContentText("Invalid username or password.");
           alert.showAndWait();
       }
   }
}

Leave a Reply