【发布时间】:2019-12-05 21:34:51
【问题描述】:
我正在学习 javafx 并正在创建一个 TodoList 应用程序。我想包含某些功能,如文本样式、使用项目符号列表等,为此我在我的应用程序中添加了一个 HTMLEditor,它存储 html 文件以供我的 WebView 加载。为了测试 html 文件的保存和加载,我保存了一个示例“test.html”文件(不在我的类路径中)并希望 WebView 加载它。 这是我的一些代码:
Main.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.web.WebView?>
<GridPane xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml" fx:controller="sample.Controller" hgap="10" vgap="10">
<WebView GridPane.rowIndex="0" GridPane.columnIndex="0" fx:id="webView"/>
</GridPane>
Fxml Controller.java
public class Controller{
@FXML private WebView webView;
private WebEngine engine = webView.getEngine();
@FXML
public void initialize() throws IOException{
//code for some ArrayList initialization
engine.load("/home/jyotiproy/TodoOutput/test.html");
}
}
加载程序的Main.java
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("Main.fxml"));
primaryStage.setTitle("Todo List");
primaryStage.setScene(new Scene(root, 1200, 600));
primaryStage.show();
primaryStage.setResizable(false);
}
public static void main(String[] args) {
launch(args);
}
}
我没有收到任何错误或异常。 “test.html”的路径中没有错字,html 编辑器工作正常并保存了 test.html,但 WebView 什么也不加载。 这是我的应用程序结构:
【问题讨论】:
-
阅读为
File。将文件内容转换为String。 -
String htmlString = new String (Files.readAllBytes(Paths.get(filePath))); -
@Sedrick 使用了以下内容:`` File f = new File("/home/jyotiproy/TodoOutput/test.html"); engine.load(f.toString());``还是什么都没有
-
WebEngine#load(String)方法需要String形式的 URL。试试"file:///home/jyotiproy/TodoOutput/test.html"之类的东西。如果您使用@Sedrick 建议的方法(即将文件的内容 读入String),那么您将需要使用WebEngine#loadContent(String)。 -
永远不要实例化打算由
FXMLLoader注入的字段。您引用的WebEngine与您创建的WebView相关联,而不是与FXMLLoader(即正在显示的那个)创建(和注入)的WebView相关联。
标签: java javafx javafx-webengine javafx-webview