javajavafxjavafx-webenginejavafx-webview

How can I load a Local html file (not in my classpath) to WebView?


I'm learning javafx and am creating a TodoList application. I want to include certain features like text styling, using bullet lists etc. and for that I have added an HTMLEditor to my app, which stores html files for my WebView to load. To test the saving and loading of the html files I have saved a sample 'test.html' file (which is not in my classpath) and want the WebView to load it. here's some of my code:

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 that loads the program

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);
    }
}

I'm getting no errors or exceptions. There is no typo in the path of the 'test.html' and the html editor works fine and saves the test.html, but the WebView loads nothing. Here is my app structure: WebView HTMLEditor


Solution

  • Thanks to @Slaw and @Sidrick the question was solved. The changes that were needed in the original code were the addition of the file:// in the engine.load() part of the code.

    Working Code

    @FXML private WebView webView;
    
    
    
        @FXML
        public void initialize() throws IOException{
            //Some ArrayList Initialization 
    
            WebEngine engine = webView.getEngine();
            engine.load("file:///home/jyotiproy/Todolist/test2.html");
        }
    

    Screenshot:

    Working app