[英]Detect URL change in JavaFX WebView
在JavaFX的WebView
我很難檢測到URL的變化。
我在課堂上有這個方法:
public Object urlchange() {
engine.getLoadWorker().stateProperty().addListener(new ChangeListener<State>() {
@Override
public void changed(ObservableValue ov, State oldState, State newState) {
if (newState == Worker.State.SUCCEEDED) {
return engine.getLocation());
}
}
});
}
我試圖將它用於名為loginbrowser的對象,如:
System.out.print(loginbrowser.urlchange());
你能看出我做錯了什么嗎?
(部分)你做錯了什么
您在問題中提供的代碼甚至無法編譯。 ChangeListener的更改方法是void函數,它不能返回任何值。
無論如何,在Web視圖中加載東西是一個異步過程。 如果您想在加載Web視圖后獲取Web視圖的位置值,則需要等待加載完成(在JavaFX應用程序線程上不可取,因為這會掛起您的應用程序,直到加載完成),或者在回調中通知負載是否完整(這是你的監聽器正在做什么)。
(可能)你想做什么
將一些屬性綁定到Web引擎的location屬性。 例如:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.scene.web.*;
import javafx.stage.Stage;
public class LocationViewer extends Application {
@Override
public void start(Stage stage) throws Exception {
Label location = new Label();
WebView webView = new WebView();
WebEngine engine = webView.getEngine();
engine.load("http://www.fxexperience.com");
location.textProperty().bind(engine.locationProperty());
Scene scene = new Scene(new VBox(10, location, webView));
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
只要Web視圖的位置發生更改,上面的代碼就會更新位置標簽(通過運行代碼然后單擊某些鏈接來嘗試)。 如果您希望僅在頁面成功加載后更新標簽,則需要基於WebView狀態的偵聽器,例如:
import javafx.application.Application;
import javafx.concurrent.Worker;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.scene.web.*;
import javafx.stage.Stage;
public class LocationAfterLoadViewer extends Application {
@Override
public void start(Stage stage) throws Exception {
Label location = new Label();
WebView webView = new WebView();
WebEngine engine = webView.getEngine();
engine.load("http://www.fxexperience.com");
engine.getLoadWorker().stateProperty().addListener((observable, oldValue, newValue) -> {
if (Worker.State.SUCCEEDED.equals(newValue)) {
location.setText(engine.getLocation());
}
});
Scene scene = new Scene(new VBox(10, location, webView));
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
如果您運行最后一個程序並單擊某些鏈接,您會注意到它會延遲更新位置標簽,直到您單擊的頁面完全加載完畢,而不是第一個程序在位置發生變化時立即更新標簽,無論負載是否需要一段時間或確實工作。
其他問題的答案
如何在條件語句中使用標簽中的url值? 我想要一個動作如果它從原來的改變了。
location.textProperty().addListener((observable, oldValue, newValue) -> {
// perform required action.
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.