Johnny
Johnny

Reputation: 1559

Size JavaFX WebView to the minimum size needed by the document body

I'm writing a custom dialog in JavaFX for my project. I need a variant but quick mode for showing the dialog content.

I know about controlsFX; actually I'm using it but I want to show the content in a WebView so it will be more controllable.

The problem is about the size of the WebView I want to find the height of the document body and set the size of the WebView to that.

I tried the following javascript hack but before showing the dialog I get 0 for the size and after showing dialog the value is not reliable. Is there a better solution or I should forget about it and try to embed a swing component that supports HTML 3?

    WebView vw = new WebView();
    vw.getEngine().loadContent("<p>This is my text</p><b>Another</b><p> This is a paragraph</p><ul><li>First cause</li><li>Second cause></li></ul>");
    vw.setPrefSize(500, 50);
    vw.setOnMouseClicked(new EventHandler<MouseEvent>() {

        @Override
        public void handle(MouseEvent event) {
            // I see that executeScript doesn't work correctly even when the WebView is loaded
            Integer h = (Integer) vw.getEngine().executeScript("document.body.offsetHeight");
            System.out.println("scriptRES: " + h );
            vw.setPrefSize(400, h);
            vw.setMinSize(400, h);
            vw.setMaxSize(400, h);
        }
    });

Upvotes: 2

Views: 1569

Answers (3)

Brad Turek
Brad Turek

Reputation: 2832

Until automatic preferred sizing is implemented, a certain blogmeister has come up with a solution that seems to work (for now).

It can be found in its original form on his website.

It makes having a preferred-size WebView as easy as

WebViewFitContent webViewFitContent = new WebViewFitContent(html);
yourContainer.getChildren().add(webViewFitContent);

WebViewFitContent in action


In case the link were to ever die,

WebViewFitContent.java

import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ListChangeListener;
import javafx.concurrent.Worker.State;
import javafx.geometry.HPos;
import javafx.geometry.VPos;
import javafx.scene.Node;
import javafx.scene.layout.Region;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import netscape.javascript.JSException;

import java.util.Set;

public final class WebViewFitContent extends Region {

    final WebView webview = new WebView();
    final WebEngine webEngine = webview.getEngine();

    public WebViewFitContent(String content) {
        webview.setPrefHeight(5);

        widthProperty().addListener(new ChangeListener<Object>() {
            @Override
            public void changed(ObservableValue<?> observable, Object oldValue, Object newValue) {
                Double width = (Double)newValue;
                webview.setPrefWidth(width);
                adjustHeight();
            }
        });

        webview.getEngine().getLoadWorker().stateProperty().addListener(new ChangeListener<State>() {
            @Override
            public void changed(ObservableValue<? extends State> arg0, State oldState, State newState)         {
                if (newState == State.SUCCEEDED) {
                    adjustHeight();
                }
            }
        });

        webview.getChildrenUnmodifiable().addListener(new ListChangeListener<Node>() {
            @Override
            public void onChanged(ListChangeListener.Change<? extends Node> change) {
                Set<Node> scrolls = webview.lookupAll(".scroll-bar");
                for (Node scroll : scrolls) {
                    scroll.setVisible(false);
                }
            }
        });

        setContent(content);
        getChildren().add(webview);
    }

    public void setContent(final String content) {
        Platform.runLater(new Runnable(){
            @Override
            public void run() {
                webEngine.loadContent(getHtml(content));
                Platform.runLater(new Runnable(){
                    @Override
                    public void run() {
                        adjustHeight();
                    }
                });
            }
        });
    }


    @Override
    protected void layoutChildren() {
        double w = getWidth();
        double h = getHeight();
        layoutInArea(webview,0,0,w,h,0, HPos.CENTER, VPos.CENTER);
    }

    private void adjustHeight() {
        Platform.runLater(new Runnable(){
            @Override
            public void run() {
                try {
                    Object result = webEngine.executeScript(
                            "var myDiv = document.getElementById('mydiv');" +
                                    "if (myDiv != null) myDiv.offsetHeight");
                    if (result instanceof Integer) {
                        Integer i = (Integer) result;
                        double height = new Double(i);
                        height = height + 20;
                        webview.setPrefHeight(height);
                    }
                } catch (JSException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private String getHtml(String content) {
        return "<html><body>" +
                "<div id=\"mydiv\">" + content + "</div>" +
                "</body></html>";
    }

}

Note 1: In the above I added a null-check in the javascript and chose to print out any exceptions that might occur instead of ignoring them.

Note 2: Sometimes the WebView's content doesn't show through. If anyone else experiences this please leave a comment.

Upvotes: 0

BerndGit
BerndGit

Reputation: 1660

This is a very late answer.

You have to apply ChangeListener on the document, before calulating the height. Kindly find a running example to your question at: Correct sizing of Webview embedded in Tabelcell

However my experience is that the high is still sometimes to big.

Upvotes: -1

jewelsea
jewelsea

Reputation: 159341

Automated sizing support of WebView is covered by a feature request in the JavaFX issue tracker:

The feature request has currently not been implemented or scheduled for implementation. You can vote for or comment on the feature request.

There is no work-around that I know of. Earlier version of WebView seemed to work with the following code engine.executeScript("document.width") and engine.executeScript("document.height"). But these commands no longer worked last time I tried them.

Upvotes: 2

Related Questions