javaFX WebView使用及打开网页

前言

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

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值