3

I want to add padding to a WebView in JavaFX, like you can add padding to a label.

I have already found this stack overflow discussion about WebView on Android, and it has bugs with the padding. However, I want to add a WebView in a BorderPane on a desktop application with padding on all sides.

I tried to use setPadding() however, this method doesn`t exist.

Is there an alternative for it?

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
GregGott
  • 95
  • 9

2 Answers2

6

You can, add a margin bottom to the label, to replace the idea of padding it, or you can use JS when load the WebView and padding inside the html. Like this:

webView.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageFinished(WebView view, String url) {
        webView.loadUrl("javascript:document.body.style.padding=\"10%\";void 0");
    }
});
Kaneda
  • 722
  • 5
  • 16
  • I didn't want to use a margin-bottom, because the code for it looks so dirty. But maybe it's the only possible solution. Inner padding with JS is a really good idea, I didn't think about this before. I don't need this for the current project, but it's really good to know. – GregGott Jul 16 '22 at 17:15
  • 3
    Note that JavaFX does not have a `WebViewClient` class. Android does. Perhaps you got the two mixed up? Though the OP does link to a Q&A that's for Android. However, the question is tagged [tag:javafx] and discusses JavaFX. And the general idea should still be possible in JavaFX. – Slaw Jul 16 '22 at 21:52
5

As shown here, you can use the BorderPane Optional Layout Constraints to add "Margin space around the outside of the child."

WebView webView = new WebView();
BorderPane.setMargin(webView, new Insets(16));
top.setCenter(webView);
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • Yes, Kaneda already mentioned this. This works perfectly. But I wonder why the `setPadding()` option is not available for WebView. However, my problem is solved, thanks. – GregGott Jul 16 '22 at 17:23
  • 4
    @GregGott This solution is not the same as Kaneda's, either in their comment or their answer. Kaneda's comment says to set the _padding_ of the entire border pane, whereas this answer sets the _margin_ of a specific child node. All within JavaFX. Kaneda's _answer_ drops into the JavaScript/HTML document of the web page and sets the padding there. Also, this answer sets the margin, not the padding. As for why `WebView` does not have a padding property, that's because it extends `Parent` and not `Region`. This makes sense. The style/layout of the web page should be up to the web page. – Slaw Jul 16 '22 at 17:50
  • 1
    @Slaw's insight is correct; also consider for [example](https://stackoverflow.com/a/33824164/230513), `StackPane` _is a_ `Region`, so `root.setPadding(new Insets(16))`. – trashgod Jul 16 '22 at 19:15
  • @Slaw Oh. Thanks for that correction, I was wrong, sorry. Thanks for explaining this. – GregGott Jul 16 '22 at 20:04