效果图:

JAVAFX应用程序嵌入本地的html文件(webview)

 

废话不多说,直接上代码。

Main类:

package sample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
        primaryStage.setTitle("JAVAFX嵌入html测试");
        primaryStage.setScene(new Scene(root, 1270, 860));
        primaryStage.show();
    }


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

 

Controller类:
package sample;

import java.net.URL;
import java.util.ResourceBundle;


import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;

public class Controller  implements Initializable {


    @FXML
    private WebView webView;


    @Override
    public void initialize(URL location, ResourceBundle resources) {
        // TODO Auto-generated method stub

        final WebEngine webengine = webView.getEngine();
        String url = Main.class.getResource("/html/index.html").toExternalForm();
        webengine.load(url);
    }
}

 

fxml文件的代码:

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.web.*?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
    <children>
        <WebView fx:id="webView" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
    </children>
</AnchorPane>


项目结构图:

JAVAFX应用程序嵌入本地的html文件(webview)

html文件夹放到src下,html文件夹里面放你的html文件。

 

 

 

相关文章:

  • 2021-11-30
  • 2022-12-23
  • 2022-12-23
  • 2021-12-31
  • 2021-06-30
  • 2022-12-23
  • 2022-02-09
  • 2021-10-02
猜你喜欢
  • 2022-01-03
  • 2021-12-01
  • 2021-11-18
  • 2021-05-18
  • 2022-01-25
  • 2021-12-17
  • 2022-02-03
相关资源
相似解决方案