WebEngine在JavaFx应用程序中加载html文件

时间:2017-08-22 11:59:07

标签: java html javafx javafx-8

我正在为大学做一个java程序。 点击菜单项上的按钮,我试着打开一个新阶段。 这个阶段必须显示html文件的内容。

打开舞台不是问题,问题是舞台是空的(打开舞台时我没有收到任何错误)。

html stage (picture)

在java程序的主控制器中,这是打开html-stage的代码:

@FXML
public void showBrowser(ActionEvent event) throws IOException {
    Stage primaryStage = new Stage();
    Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("othello/view/browser.fxml"));
    Scene scene = new Scene(root);

    primaryStage.setScene(scene);
    primaryStage.setResizable(false);
    primaryStage.sizeToScene();
    primaryStage.setTitle("Team Background");
    primaryStage.show();
} }

这是我想要显示的html阶段的fxml文件(browser.fxml):

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

<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.web.WebView?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="othello.controller.WebViewController">
   <children>
      <WebView fx:id="webView" layoutX="100.0" prefHeight="400.0" prefWidth="600.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
   </children>
</AnchorPane>

这是fxml文件(WebViewController)的控制器代码:

package othello.controller;

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

public class WebViewController {
   @FXML
   public WebView webView;
   public WebEngine webEngine;

   private void initialize() {

webEngine = webView.getEngine();
webEngine.load(getClass().getResource("/Othello/src/othello/html/TeamBackground/history.html").toExternalForm());



    }
}

我还尝试使用.hmtl文件的路径加载为URL或文件而没有任何结果。 你能帮帮我吗?

最诚挚的问候。

1 个答案:

答案 0 :(得分:0)

我尝试像你的代码一样实现我发现你的错误,你使用了从src文件夹开始的错误的html文件路径,但是当你使用getClass()。getResource()时,你当前在资源文件夹 src 所以请更正您的路径:

  webEngine.load(getClass().getResource("/othello/html/TeamBackground/history.html").toExternalForm());