Reputation: 5233
Is that possible to open local text file with JavaFX WebView ? I have tried the following code but it was not working. How can I enable this?
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();
}
});
wv.getEngine().loadContent("<a href="file:///C:\Users\Dev\infor.txt">Open File</a>");
StackPane root = new StackPane();
root.getChildren().add(wv);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
Upvotes: 0
Views: 3004
Reputation: 159416
Yes, you can open a local text file with a JavaFX WebView.
Sample app:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
public class WebViewWithLocalText extends Application {
@Override
public void start(Stage stage) throws MalformedURLException {
String location =
new File(
System.getProperty("user.dir") + File.separator + "test.txt"
).toURI().toURL().toExternalForm();
System.out.println(location);
WebView webView = new WebView();
webView.getEngine().load(location);
// use loadContent instead of load if you want a link to a file.
// webView.getEngine().loadContent(
// "<a href=\"" + location + "\">Open File</a>"
// );
Scene scene = new Scene(webView);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Place a text file at the location reported by System.out when you run the program.
Sample output:
Some errors in your supplied code:
I don't have a windows machine to test, but perhaps something like this would work for your absolute path.
wv.getEngine().loadContent("<a href=\"file:///C:/Users/Dev/infor.txt\">Open File</a>");
See also:
Upvotes: 2