如何使用WebView和WebEngine编写JavaFX中的后退和前进按钮?

Fra*_*ank 4 javafx button back forward

我正在学习JavaFX,尝试编写一个简单的浏览器,但是如何使用WebView和WebEngine编写JavaFX中的后退和前进按钮?任何示例代码?

Fra*_*ank 7

我想到了 :

  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();
  }
Run Code Online (Sandbox Code Playgroud)


小智 7

“我想通了”下的代码是如何对按钮进行编码的一个很好的例子,除了如果按原样运行它,它会抛出越界异常。例如,如果用户在 WebEngine 浏览器首次加载时单击返回,就会发生这种情况。在这种情况下,entryList 的长度为 1,并且调用 history.goBack(-1) 尝试访问 entryList 当前位置减 1(即 0 - 1)的 entryList,这是越界的。当 currentIndex 已经是 entryList 的末尾时,调用 history.go(1) for goForward 存在类似的情况,在这种情况下,调用尝试访问超出其长度的索引处的列表,再次超出范围。

下面的简单示例代码在任何时间点处理条目列表的边界:

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); 
  });    
}
Run Code Online (Sandbox Code Playgroud)


小智 6

如果您不需要获取或设置任何索引,这是使用javascript编写自定义contextMenu的后退和前进按钮的一种简洁方法:

public void goBack() {
    Platform.runLater(() -> {
        webEngine.executeScript("history.back()");
    });
}

public void goForward() {
    Platform.runLater(() -> {
        webEngine.executeScript("history.forward()");
    });
}
Run Code Online (Sandbox Code Playgroud)