Work
Work

Reputation: 23

The method "resize()" does not work for Webview in JavaFX

In a part of my code, I want to change a WebView object's size. Here is that part of code:

    textbox.setOnKeyPressed(new EventHandler<KeyEvent>() {
    @Override
    public void handle(KeyEvent ke) {
        if(ke.getCode() == KeyCode.ENTER){

            System.out.println("Enter pressed!");
            if(webEngine.isResizable())
                  System.out.println("It's Resizable!");
            webEngine.resize(300,200);     //doesn't work!

        }
    }
    });

It compiles and runs without giving errors and "Enter pressed!" and "It's Resizable!" messages are shown on the console when I press enter, yet the webEngine object does not change in size!!!

Can anybody help me about that? Thanks.

Upvotes: 1

Views: 599

Answers (1)

Matt
Matt

Reputation: 3187

You should try putting your WebView inside of a container of your choice and then resize the container you should also put brackets around your if statement and add the resize in that like so

VBox vbox = new VBox();
vbox.getChildren().add(webView);
if(vbox.isResizable()){
    System.out.println("It's Resizable!");
    vbox.resize(300,200);     //doesn't work!
}

I ran this code to test it and it ran perfectly by that I mean it resized

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {
        VBox vbox = new VBox();
        TextField textbox = new TextField();
        WebView webView = new WebView();
        WebEngine webEngine = webView.getEngine();
        webEngine.load("https://www.google.com/");

        textbox.setOnKeyPressed(ke -> {
            if(ke.getCode() == KeyCode.ENTER){

                System.out.println("Enter pressed!");

                if(vbox.isResizable()) {
                    System.out.println("It's Resizable!");
                    vbox.resize(300, 200);     //doesn't work!
                }
            }
        });

        vbox.getChildren().addAll(textbox,webView);
        Scene scene = new Scene(vbox);
        Stage stage = new Stage();
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) { launch(args); }
}

Upvotes: 2

Related Questions