0 Replies Latest reply on Jun 21, 2019 10:18 PM by Roxy rollers

    JavaFX: How to manage focusedProperty between different nodes?

    Roxy rollers

      I have a listener attached to my studentIDText field that fetches the Student record from the database. The StudentIdText field cannot be empty, so if you try to tab out of it, it should give me an error message. I should however be able to click on the Exit button and leave. I seem to have the focus still on StudentIdText field and the error message keeps popping up when I try to exit the screen.

      When clicking on the Exit button, I have tried to set the focus on a different field (In this case a hidden one). I have also tried it on another field like First Name but the alert will not go away. Any help in this regard is greatly appreciated.

      // StudentController.java
      public class StudentController {
      @FXML private TextField studentIdText;
      @FXML private TextField lastNameText;
      @FXML private TextField firstNameText;

      //Exit the program
      @FXML
      public void handleExit(ActionEvent actionEvent) {
         hiddenText
      .requestFocus();
        
      System.exit(0);
      }

      @FXML
      public static void showErrorMessage(String infoMessage, String titleBar, String headerMessage)
      {
       
      Alert alert = new Alert(AlertType.ERROR);
        alert
      .setTitle(titleBar);
        alert
      .setHeaderText(headerMessage);
        alert
      .setContentText(infoMessage);
        alert
      .showAndWait();
      }

      @FXML
      private void initialize () {
      // Listener to studentIdText field
        studentIdText
      .focusedProperty().addListener((arg0, oldPropertyValue, newPropertyValue) -> {
        
      if (!newPropertyValue) {
            searchStudent
      ();
        
      }
      });

      @FXML
      private void searchStudent() throws ClassNotFoundException, SQLException {
         
      if (!studentIdText.getText().isEmpty()) {
             
      //Get Student information
             
      Student stu = StudentDAO.searchStudent(studentIdText.getText());
              populateAndShowStudent
      (stu);
         
      }

             else {
                showErrorMessage
      ("Enter valid Student ID#", "Student DB", "");
                studentIdText
      .requestFocus();
            
      }

      }