Share the post "How To Fit WebView Height Based On Its Content In Java FX 2.2"
There is no way in the API to do this. However, Frode Johansen made a custom class that inherited Region and placed a WebView control inside it, then adjusting its height based on the document height after it has loaded its content by executing a Javascript one-liner code in order to retrieve the height value.
A very big thank you because considering that the Label control cannot display formatted HTML content, the only way to work around this limitation is to create a custom class of it. Luckily, he has saved us all the trouble of making one.
Here is the custom class.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
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(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("document.getElementById('mydiv').offsetHeight"); if (result instanceof Integer) { Integer i = (Integer) result; double height = new Double(i); height = height + 20; webview.setPrefHeight(height); webview.getPrefHeight()); } } catch (JSException e) { } } }); } private String getHtml(String content) { return "<html><body>" + "<div id=\"mydiv\">" + content + "</div>" + "</body></html>"; } } |
