前言

JavaFX WebView ( javafx.scene.web.WebView) 组件能够在 JavaFX 应用程序中显示网页(HTML、CSS、SVG、JavaScript)。

因此,JavaFXWebView是一个迷你浏览器。WebView 当您需要显示文档(例如帮助文本)、新闻、博客文章或其他需要在运行时从 Web 服务器下载的内容时, 该组件非常方便。

JavaFXWebView在内部使用 WebKit 开源浏览器引擎来呈现网页。

如果你还没安装javaFx 可参考我另一篇文章安装: javaFX安装及使用

一、使用WebView打开百度


import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.*;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import java.io.*;

public class MainServer extends Application {
    @Override
    public void start(Stage stage) throws IOException {
	    stage.setTitle("JavaFX WebView Example");
        WebView webView = new WebView();
        webView.getEngine().load("http://www.baidu.com");
        StackPane root = new StackPane();
        root.getChildren().add(webView);
        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.show();
    }

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

效果如下:
在这里插入图片描述

二、使用WebView打开本地html


import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;

public class MainServer extends Application {
    @Override
    public void start(Stage stage) throws IOException {
        stage.setTitle("本地html");
        File f = new File("F:\\diff.html");
        WebView webView = new WebView();
        try {
            webView.getEngine().load(f.toURI().toURL().toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        webView.getEngine().executeScript( "window.getComputedStyle(document.body, null).getPropertyValue('height')" );
        StackPane root = new StackPane();
        root.getChildren().add(webView);
        Scene scene = new Scene(root);

        stage.setScene(scene);
        stage.show();
    }

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

效果如下:
在这里插入图片描述


如果你对 javaFX 感兴趣,你可以看下我 gitgub上使用 javaFX 开发的一个应用: XTool

在这里插入图片描述

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐