如何通过单击按钮清除javaFX的WebView内容?

时间:2015-04-16 18:00:14

标签: web view javafx

我想知道如何通过单击带有javaFX的按钮来清除webview的内容?那我该怎么做呢?例如:如果此页面清除,则WebView1包含Google网页,而单击按钮

1 个答案:

答案 0 :(得分:5)

您可以通过加载一些空白内容来清除网页视图:

webView.getEngine().loadContent("");

完整示例:

import java.util.regex.Pattern;

import javafx.application.Application;
import javafx.geometry.Insets;
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.web.WebView;
import javafx.stage.Stage;

public class WebBrowser extends Application {

    private TextField textField ;
    private WebView webView ;

    @Override
    public void start(Stage primaryStage) {
        webView = new WebView();
        textField = new TextField("https://www.google.com");
        textField.setOnAction(e -> load());
        load();

        Button clearButton = new Button("Clear");
        clearButton.setOnAction(e -> webView.getEngine().loadContent(""));
        BorderPane root = new BorderPane(webView, new HBox(10, textField, clearButton), null, null, null);

        textField.setPadding(new Insets(5));
        root.setPadding(new Insets(5));
        Scene scene = new Scene(root, 800, 600);
        primaryStage.setScene(scene);
        primaryStage.show();
    }


    private void load() {
        String url = makeUrl(textField.getText()) ;
        webView.getEngine().load(url);
        textField.setText(url);
    }


    private String makeUrl(String text) {
        if (Pattern.matches("[a-zA-Z]+:.+", text)) {
            return text ;
        } else return "http://"+text ;
    }

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