javamultithreadingtimerjavafxkeyrelease

What to use to create search engine using onKeyReleased event


I am trying to create a search bar which will search the entered string or character from db. While first character is typed in textfield it should wait for next 200ms, if next character is entered within that time then it will restart the counter and again wait for next 200ms if not, then it will search from db.

Here is some code which i tried but not work for me

@FXML protected void keyReleased(KeyEvent evt)throws Exception {
   if (evt.getCode() != KeyCode.BACK_SPACE) {
       String ch = evt.getText();
       String[] myArray = new String[5];
       run();
       searchFrmDb(ch, myArray);
   }
}
public void run(){
   for(int i=1;i<5;i++){
      try{
          Thread.sleep(200);
      }catch(InterruptedException e){System.out.println(e);}
     System.out.println(i);

    } 
}
public void searchFrmDb(String ch,String[] myArray){
     //db search operation ...
}

I am new in java help me out to sort out my problem What should i use thread or Timer or anything else


Solution

  • Consider using a PauseTransition for functionality like this.

    public class ControllerClass {
    
        private final PauseTransition pauseBeforeSearch = new PauseTransition(Duration.millis(200));
    
        @FXML protected void keyReleased(KeyEvent evt)throws Exception {
           if (evt.getCode() != KeyCode.BACK_SPACE) {
               pauseBeforeSearch.setOnFinished(e -> {
                   searchFrmDb(evt.getText(), new String[5]);
               });
               pauseBeforeSearch.playFromStart();
           }
        }
    
    }