What to use to create search engine using onKeyReleased event

170 views Asked by At

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

2

There are 2 answers

5
James_D On BEST ANSWER

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();
       }
    }

}
2
Nick ten Veen On

I would have a look at java.util.Timer and java.util.TimerTask:

class SearchTimerTask extends TimerTask{
    @Override
    public void run(){
        searchFrmDb();
    }

    @Override
    public void cancel(){
        super.cancel();
        //handle cancellation logic if necessary
    }
}

Keep a reference to a Timer and a TimerTask somewhere:

Timer timer = new Timer();
TimerTask task;

Then in your key event handler you simply cancel the current task if there is one and fire up a new one:

@FXML protected void keyReleased(KeyEvent evt)throws Exception {
   if (evt.getCode() != KeyCode.BACK_SPACE) {
        if(task != null){
            task.cancel();
            task = new SearchTimerTask();
        }
        timer.schedule(task, 200);
   }
}