2013-04-01 34 views
4

如何在JavaFx中获取webview控件的文档高度?JavaFX webview,获取文档高度

+0

Java和JavaScript有很大的不同。另外,请扩展您的问题,或许您已经尝试过。 –

+0

我有一个webview控件,我想设置它的高度相对于文档高度。 –

+0

请点击编辑更新您的问题。您的评论仅仅重新排列了原始问题中的单词! –

回答

5

你可以使用下面的调用在WebView中显示的文档的高度:

webView.getEngine().executeScript(
    "window.getComputedStyle(document.body, null).getPropertyValue('height')" 
); 

一个完整的应用程序来演示调用用法:

import javafx.application.Application; 
import javafx.beans.value.*; 
import javafx.scene.Scene; 
import javafx.scene.web.*; 
import javafx.stage.Stage; 
import org.w3c.dom.Document; 

public class WebViewHeight extends Application { 
    @Override public void start(Stage primaryStage) { 
    final WebView webView = new WebView(); 
    final WebEngine engine = webView.getEngine(); 
    engine.load("http://docs.oracle.com/javafx/2/get_started/animation.htm"); 
    engine.documentProperty().addListener(new ChangeListener<Document>() { 
     @Override public void changed(ObservableValue<? extends Document> prop, Document oldDoc, Document newDoc) { 
     String heightText = webView.getEngine().executeScript(
      "window.getComputedStyle(document.body, null).getPropertyValue('height')" 
     ).toString(); 
     double height = Double.valueOf(heightText.replace("px", ""));  

     System.out.println(height); 
     } 
    }); 
    primaryStage.setScene(new Scene(webView)); 
    primaryStage.show(); 
    } 

    public static void main(String[] args) { launch(args); } 
} 

以上答案的来源:Oracle JavaFX forums WebView configuration thread。对于相关功能的基于Java API


相关问题跟踪请求:

RT-25005 Automatic preferred sizing of WebView

+0

它的工作原理,但结果是不正确的。我通过像素线测量,高度约为480px,代码返回414px。 – 2015-06-05 05:54:25

+0

谢谢你的泽。这有点迟了。你的例子正在运行。不过,我有一个嵌入在“TableCell”中的webview。这里的结果总是0像素(关闭:https://stackoverflow.com/questions/22334983/java-fx-tableview-display-simple-html/22335276#22335276)任何想法如何解决这个问题? – BerndGit

+0

请参阅:https://stackoverflow.com/questions/42856471/workaround-for-rt-25005-automatic-preferred-sizing-of-webview以获取更具体的问题,包括运行示例。 – BerndGit

0

这是你在找什么:

Double.parseDouble(webView.getEngine().executeScript("document.height").toString())