目前我有一个TextField,它是我的地址栏和一个WebView,它是我的页面。当我点击进入时,TextField似乎什么也没做。这意味着运行loadPage方法并设置为page以加载用户输入到地址栏中的任何内容。任何帮助将不胜感激。
package javafx_webview;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
public class Main extends Application {
WebEngine myWebEngine;
public static void main(String[] args) {
launch(args);
}
public void start(Stage primaryStage) {
primaryStage.setTitle("Platinum v1");
TextField addressBar = new TextField();
addressBar.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
loadPage(event.toString());
}
});
WebView myBrowser = new WebView();
myWebEngine = myBrowser.getEngine();
StackPane root = new StackPane();
root.getChildren().add(myBrowser);
root.getChildren().add(addressBar);
primaryStage.setScene(new Scene(root, 640, 480));
primaryStage.show();
}
private void loadPage(String url) {
try {
myWebEngine.load(url);
} catch (Exception e) {
System.out.println("The URL you requested could not be found.");
}
}
}
答案 0 :(得分:6)
从地址栏的text
获取网址,而不是地址栏上操作事件的toString
。
final TextField addressBar = new TextField();
addressBar.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
myWebEngine.load(addressBar.getText());
}
});
此外,加载是异步的,因此您的异常处理程序将不起作用。您需要监视webengine loadworker的exception属性以从引擎获取异常。另请注意,未找到的URL不一定是报告的异常,而是Web服务器通常会返回页面以显示http 404错误。
以下是一份工作样本:
import javafx.application.Application;
import javafx.beans.value.*;
import javafx.event.*;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.scene.web.*;
import javafx.stage.Stage;
public class Main extends Application {
private WebEngine myWebEngine;
public void start(Stage stage) {
stage.setTitle("Platinum v1");
final TextField addressBar = new TextField();
addressBar.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
myWebEngine.load(addressBar.getText());
}
});
WebView myBrowser = new WebView();
myWebEngine = myBrowser.getEngine();
myWebEngine.getLoadWorker().exceptionProperty().addListener(new ChangeListener<Throwable>() {
@Override public void changed(ObservableValue<? extends Throwable> observableValue, Throwable oldException, Throwable exception) {
System.out.println("WebView encountered an exception loading a page: " + exception);
}
});
VBox root = new VBox();
root.getChildren().setAll(
addressBar,
myBrowser
);
stage.setScene(new Scene(root));
stage.show();
}
public static void main(String[] args) { launch(args); }
}