How to program Back and Forward buttons in JavaFX with WebView and WebEngine?

Frank picture Frank · Sep 21, 2013 · Viewed 8k times · Source

I'm learning JavaFX, trying to write a simple browser, but how do I program the Back and Forward buttons in JavaFX with WebView and WebEngine ? Any sample code ?

Answer

Frank picture Frank · Sep 24, 2013

I figured it out :

  public String goBack()
  {    
    final WebHistory history=eng.getHistory();
    ObservableList<WebHistory.Entry> entryList=history.getEntries();
    int currentIndex=history.getCurrentIndex();
//    Out("currentIndex = "+currentIndex);
//    Out(entryList.toString().replace("],","]\n"));

    Platform.runLater(new Runnable() { public void run() { history.go(-1); } });
    return entryList.get(currentIndex>0?currentIndex-1:currentIndex).getUrl();
  }

  public String goForward()
  {    
    final WebHistory history=eng.getHistory();
    ObservableList<WebHistory.Entry> entryList=history.getEntries();
    int currentIndex=history.getCurrentIndex();
//    Out("currentIndex = "+currentIndex);
//    Out(entryList.toString().replace("],","]\n"));

    Platform.runLater(new Runnable() { public void run() { history.go(1); } });
    return entryList.get(currentIndex<entryList.size()-1?currentIndex+1:currentIndex).getUrl();
  }