WebView没有显示任何内容

时间:2015-06-05 21:29:21

标签: java javafx-8

我有一个非常简单的应用程序,它在tableview中列出数据库中的行。当用户单击该列表中的行时,应用程序从该行获取XML列,并且应该在同一窗口中的WebView中显示它。除了实际显示XML之外的所有内容都可以正常工作。我已经在这上面打了一段时间,但我没有到达任何地方。这是侦听器调用的代码:

    @FXML
    private void showXML(QueryRow row) {

        String msg = "";
        try {
            msg = mainApp.getMsg(row.getID().get());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        final String fm = msg;

        System.out.println(msg);

        //tb.setText(msg);

        webEngine = webView.getEngine();
//      webEngine.getLoadWorker().stateProperty().addListener(new ChangeListener<State>() {
//        
//          public void changed(ObservableValue ov, State oldState, State newState) {
//
//            if (newState == Worker.State.SUCCEEDED) {
//              System.out.println("inside");
//              webEngine.load(fm);
//              //stage.setTitle(webEngine.getLocation());
//            }
//
//          }
//        });
        System.out.println("Go baby go!");
        webEngine.load(fm);

    }

我错过了什么?

2 个答案:

答案 0 :(得分:1)

如果您要加载XML并且fm不是链接,那么您应该使用

webEngine.loadContent(fm);

/**
 * Loads the given HTML content directly. This method is useful when you have an HTML
 * String composed in memory, or loaded from some system which cannot be reached via
 * a URL (for example, the HTML text may have come from a database). As with
 * {@link #load(String)}, this method is asynchronous.
 */
public void loadContent(String content) {
    loadContent(content, "text/html");
}

但是这不会使xml可见,所以如果你想要显示你的xml,你必须将它放在一些默认的html页面中。像这样的东西: https://gist.github.com/jewelsea/1463485

或简单的方式:

webEngine.loadContent(
         <textarea readonly style='width:100%; height:100%'>"+ fm +"</textarea>")

答案 1 :(得分:1)

好的,我刚刚测了一下。 text / html是正确的方法,但你需要对你的xml数据做一些工作:你必须转义XML实体(我使用commons-lang3 StringEscapeUtils),然后将所有内容包装在一个预格式化的html字符串中:

public class JavaFXTest extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setTitle("Test to display XML");

        BorderPane content = new BorderPane();
        WebView webView = new WebView();
        WebEngine webEngine = webView.getEngine();

        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<tag1>\n  <tag2>hello</tag2>\n</tag1>";
        String escaped = StringEscapeUtils.escapeHtml4(xml);
        String html = "<html><head></head><body><pre>" + escaped + "</pre></body>";

        webEngine.loadContent(html, "text/html");

        content.setCenter(webView);
        primaryStage.setScene(new Scene(content, 400, 300));
        primaryStage.show();
    }

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

这会产生以下窗口:

enter image description here

补充:你可能需要在转义之前在xml上做一些漂亮的打印;我刚刚使用了硬编码的换行符和空格。