我必须使用JavaFX(2.2)WebView显示一些值。但价值必须查询表单数据库。此值可能包含对外部网页和内部本地文件的一些引用。如何使用户能够使用WebView打开这些网页和本地文件。谢谢。
WebView wv = new WebView();
wv.getEngine().setCreatePopupHandler(new Callback<PopupFeatures, WebEngine>() {
@Override
public WebEngine call(PopupFeatures p) {
Stage stage = new Stage(StageStyle.UTILITY);
WebView wv2 = new WebView();
stage.setScene(new Scene(wv2));
stage.show();
return wv2.getEngine();
}
});
String value = "<a href='http://stackoverflow.com' target='_blank'>Open a URL</a>" +
" <a href=\"file:///C:\\Users\\Dev\\debug.log\">Open a File</a> ";
wv.getEngine().loadContent(value);
StackPane root = new StackPane();
root.getChildren().add(wv);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
答案 0 :(得分:2)
我已按照以下方式解决了这个问题。为了启用此功能,以下stackoverflow post非常有用。谢谢。
// Set HostService inherit from Application class
ServiceUtil.hostServices = getHostServices();
// HTML code
final String htmlCode = "<a href='http://stackoverflow.com ' target='_blank'>Open a Web URL</a>" +
"<a href=\"file:///C:\\Users\\Dev\\debug.log\">Open a Local File</a> ";
// Create a WebView
final WebView webView = new WebView();
webView.getEngine().loadContent(htmlCode);
webView.getEngine().locationProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, final String oldValue, final String newValue) {
if((newValue != null) && (!newValue.trim().equals(""))) {
Platform.runLater(new Runnable() {
@Override
public void run() {
// Reset content as HTML codes
// NB: This will make stop opening URL in WebView
webView.getEngine().loadContent(htmlCode);
// Direct URL to local browser
ServiceUtil.hostServices.showDocument(newValue);
}
});
}
}
});