效果图:
废话不多说,直接上代码。
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> 项目结构图:
html文件夹放到src下,html文件夹里面放你的html文件。