javafunctionjavafxtextfieldjavafx-webengine

Get user input from textfield to load website of their choice


I'm making a web browser using JavaFX and currently running into an issue. The function that have to allow the user to visit any site they want doesn't work. What I tried to do is use the getText() method to obtain the url that the use entered in the textfield, then it will use webEngine.load() and add http:// before the input. Afterwards it will be put inside parethesis of WebEngine.load to load the website of the user's choice.

However this does not work. What I have tried to get to the root of the problem is I made a button just for the function to go to a specific site. That worked perfectly. I have also tried to create a new webView setup just so I can get the browser to essentially "start fresh" but with the website that the user entered. But that didn't work either.

This is my code for reference:

package application;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.text.Text;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebHistory;
import javafx.scene.web.WebView;

public class Main extends Application {
    private BorderPane root;
    private WebView webView;
    private WebEngine webEngine;
    private HBox addressBar;
    private HBox statusBar;
    private Text domain;
    private WebHistory history;
    
    private final String homePage = "https://google.ca";
    
    private void setupAddressBar() {
        addressBar = new HBox();
        Button home = new Button("Home");
        Button back = new Button("<--");
        Button forward = new Button("-->");
        Button refresh = new Button("Refresh");
        
        Button load = new Button("Load");
        
        TextField url = new TextField();
        addressBar.getChildren().addAll(home,back,forward,refresh,url, load);
        
        class HomeButton implements EventHandler<ActionEvent>{
            @Override
            public void handle(ActionEvent e) {
                homePage();
            }
        }
        
        class BackButton implements EventHandler<ActionEvent>{
            @Override
            public void handle(ActionEvent e) {
                back();
            }
        }
        
        class ForwardButton implements EventHandler<ActionEvent>{
            @Override
            public void handle(ActionEvent e) {
                forward();
            }
        }
        
        class RefreshButton implements EventHandler<ActionEvent>{
            @Override
            public void handle(ActionEvent e) {
                refreshPage();
            }
        }
        
        class DomainBar implements EventHandler<ActionEvent>{
            @Override
            public void handle(ActionEvent e) {
                loadPage();
            }
        }
        
        class LoadPage implements EventHandler<ActionEvent>{
            @Override
            public void handle(ActionEvent e) {
                loadPage();
            }
        }
        
        /*
         class KeyboardPressedHandler implements EventHandler<KeyEvent>{
                @Override
                public void handle(KeyEvent event) {
                    KeyCode key = event.getCode();
                    
                    if(key == KeyCode.ENTER ) {
                        loadPage();
                    }
                }
            };
        */  

        HomeButton homeButton = new HomeButton();
        home.setOnAction(homeButton);
        
        BackButton backButton = new BackButton();
        back.setOnAction(backButton);
        
        ForwardButton forwardButton = new ForwardButton();
        forward.setOnAction(forwardButton);
        
        RefreshButton refreshButton = new RefreshButton();
        refresh.setOnAction(refreshButton);
        
        DomainBar domainBar =  new DomainBar();
        url.setOnAction(domainBar);
        
        LoadPage loadPage = new LoadPage();
        load.setOnAction(loadPage);
    }
        
    private void setupStatusBar() {
        statusBar = new HBox();
            domain = new Text("google.ca");
            Text separator = new Text("|");
            Text copyright = new Text("JavaFX -- All Rights Reserved.");
            
            statusBar.getChildren().addAll(domain, separator, copyright);
    }
    
    public void setupWebView() {
        webView = new WebView();
        webEngine = webView.getEngine();
        webEngine.load(homePage);
    }
    
    public void initialize(URL arg0, ResourceBundle arg1) {
        webEngine = webView.getEngine();
        loadPage();
    }
    
    public void loadPage() {
        webEngine.load("http://" + domain.getText());
    }
    
    public void homePage() {
        webEngine.load("http://google.ca");
    }
    
    public void refreshPage() {
        webEngine.reload();
    }
    
    public void forward() {
        history = webEngine.getHistory();
        ObservableList<WebHistory.Entry> entries = history.getEntries();
        history.go(1);
        domain.setText(entries.get(history.getCurrentIndex()).getUrl());
    }
    
    public void back() {
        history = webEngine.getHistory();
        ObservableList<WebHistory.Entry> entries = history.getEntries();
        history.go(-1);
        domain.setText(entries.get(history.getCurrentIndex()).getUrl());
    }
    
    public void start(Stage stage) {
        root = new BorderPane();

        this.setupAddressBar();
        this.setupWebView();
        this.setupStatusBar();

        root.setTop(addressBar);
        root.setBottom(statusBar);
        root.setCenter(webView);
        
        Scene scene = new Scene(root);
        stage.setScene(scene);
        //stage.getFullScreen(true);
        stage.setWidth(1200);
        stage.setHeight(1000);
        stage.setResizable(false);
        stage.setTitle("JavaFX Browser");
        stage.show();
    }
    
    public static void main(String[] args) {
        launch(args);
    }
}

Solution

  • The only problem here is that you're using the value of you're Text domain node instead of the one from TextField url, that you should declare as a field of your class.

    It looks puzzling because you don't show any signal informing you that the page is being loaded or has an error. Putting a few logs here and there and using a debugger would help a lot.

    Also, just a side remark: waiting for you Stage to be shown before loading your home page makes more sense and might keep you out of some trouble.

    Here's a barely edited version that works:

    package com.ahpcservices.test.SoWebview;
    
    import java.net.URL;
    import java.util.ResourceBundle;
    import javafx.application.Application;
    import javafx.collections.ObservableList;
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.stage.Stage;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.control.TextField;
    import javafx.scene.layout.BorderPane;
    import javafx.scene.layout.HBox;
    import javafx.scene.text.Text;
    import javafx.scene.web.WebEngine;
    import javafx.scene.web.WebHistory;
    import javafx.scene.web.WebView;
    
    public class Main extends Application {
      private BorderPane root;
      private WebView webView;
      private WebEngine webEngine;
      private HBox addressBar;
      private HBox statusBar;
      private Text domain;
      private TextField url;
      private WebHistory history;
    
      private final String homePage = "https://google.ca";
    
      // ------------------------------------------------------
    
      private void setupAddressBar() {
        addressBar = new HBox();
        Button home = new Button("Home");
        Button back = new Button("<--");
        Button forward = new Button("-->");
        Button refresh = new Button("Refresh");
    
        Button load = new Button("Load");
    
        url = new TextField();
        addressBar.getChildren().addAll(home, back, forward, refresh, url, load);
    
        class HomeButton implements EventHandler<ActionEvent> {
    
          @Override
          public void handle(ActionEvent e) {
            homePage();
    
          }
        }
    
        class BackButton implements EventHandler<ActionEvent> {
    
          @Override
          public void handle(ActionEvent e) {
    
            back();
    
          }
        }
    
        class ForwardButton implements EventHandler<ActionEvent> {
    
          @Override
          public void handle(ActionEvent e) {
    
            forward();
    
          }
        }
    
        class RefreshButton implements EventHandler<ActionEvent> {
    
          @Override
          public void handle(ActionEvent e) {
    
            refreshPage();
          }
        }
    
        class DomainBar implements EventHandler<ActionEvent> {
    
          @Override
          public void handle(ActionEvent e) {
            loadPage();
          }
        }
    
        class LoadPage implements EventHandler<ActionEvent> {
    
          @Override
          public void handle(ActionEvent e) {
            loadPage();
          }
        }
    
        /*
         * class KeyboardPressedHandler implements EventHandler<KeyEvent>{
         * 
         * @Override public void handle(KeyEvent event) {
         * 
         * KeyCode key = event.getCode();
         * 
         * if(key == KeyCode.ENTER ) { loadPage();
         * 
         * } } };
         */
    
        HomeButton homeButton = new HomeButton();
        home.setOnAction(homeButton);
    
        BackButton backButton = new BackButton();
        back.setOnAction(backButton);
    
        ForwardButton forwardButton = new ForwardButton();
        forward.setOnAction(forwardButton);
    
        RefreshButton refreshButton = new RefreshButton();
        refresh.setOnAction(refreshButton);
    
        DomainBar domainBar = new DomainBar();
        url.setOnAction(domainBar);
    
        LoadPage loadPage = new LoadPage();
        load.setOnAction(loadPage);
    
      }
    
      // ----------------------------------------------------
      private void setupStatusBar() {
        statusBar = new HBox();
        domain = new Text("google.ca");
        Text separator = new Text("|");
        Text copyright = new Text("JavaFX -- All Rights Reserved.");
    
        statusBar.getChildren().addAll(domain, separator, copyright);
    
      }
    
      // -------------------------------------------------
      public void setupWebView() {
        webView = new WebView();
        webEngine = webView.getEngine();
      }
    
      public void initialize(URL arg0, ResourceBundle arg1) {
        webEngine = webView.getEngine();
        loadPage();
    
      }
    
      public void loadPage() {
    
        webEngine.load("http://" + url.getText());
      }
    
      public void homePage() {
        webEngine.load("http://google.ca");
      }
    
      public void refreshPage() {
        webEngine.reload();
      }
    
      public void forward() {
        history = webEngine.getHistory();
        ObservableList<WebHistory.Entry> entries = history.getEntries();
        history.go(1);
        domain.setText(entries.get(history.getCurrentIndex()).getUrl());
      }
    
      public void back() {
        history = webEngine.getHistory();
        ObservableList<WebHistory.Entry> entries = history.getEntries();
        history.go(-1);
        domain.setText(entries.get(history.getCurrentIndex()).getUrl());
      }
    
      public void start(Stage stage) {
        root = new BorderPane();
        // ---------------------------------
        this.setupAddressBar();
        this.setupWebView();
        this.setupStatusBar();
        // ----------------------------------
        root.setTop(addressBar);
        root.setBottom(statusBar);
        root.setCenter(webView);
    
        // ----------------------------------
    
        Scene scene = new Scene(root);
        stage.setScene(scene);
        // stage.getFullScreen(true);
        stage.setWidth(1200);
        stage.setHeight(1000);
        stage.setResizable(false);
        stage.setTitle("JavaFX Browser");
        stage.setOnShown(e -> {
          webEngine.load(homePage);
        });
        stage.show();
        ;
      }
    
      public static void main(String[] args) {
        launch(args);
      }
    }