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

I am learning JavaFX trying to write a simple browser, but how can I program the Back and Forward buttons in JavaFX using WebView and WebEngine? Any code sample?

+4
source share
3 answers

I understood:

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

if you don't need to get or set any indexes, here is a short way with javascript to encode back and forth buttons for custom contextMenu:

 public void goBack() { Platform.runLater(() -> { webEngine.executeScript("history.back()"); }); } public void goForward() { Platform.runLater(() -> { webEngine.executeScript("history.forward()"); }); } 
+4
source

The code under β€œI understand this” is a good example of how to encode buttons, except that if you run it as it is, it excludes exceptions from the borders. This happens if the user clicks the button when the WebEngine browser loads, for example. In this case, entryList is 1 in length, and the call to history.goBack (-1) tries to access the entryList element at its current position minus 1 (i.e. 0 - 1), which is beyond the scope. A similar situation exists for calling history.go (1) for goForward, when currentIndex is already the end of entryList, in which case the call tries to access a list with an index outside its length, again outside the bounds.

The simple sample code below refers to the boundaries of a list of records at any given time:

 public void goBack() { final WebHistory history = webEngine.getHistory(); ObservableList<WebHistory.Entry> entryList = history.getEntries(); int currentIndex = history.getCurrentIndex(); Platform.runLater(() -> { history.go(entryList.size() > 1 && currentIndex > 0 ? -1 : 0); }); } public void goForward() { final WebHistory history = webEngine.getHistory(); ObservableList<WebHistory.Entry> entryList = history.getEntries(); int currentIndex = history.getCurrentIndex(); Platform.runLater(() -> { history.go(entryList.size() > 1 && currentIndex < entryList.size() - 1 ? 1 : 0); }); } 
+3
source

All Articles