我是 Java 和 JavaFX 新手。我不知道如何将变量matched
从Browser
实现 Web 引擎的 () 类传递回 Application ( MyScene
) 类。下面列出了这两个类。我明白(我是对的吗?)它应该在变量更新之后,在页面加载之后完成。我想有两种方法可以做到这一点:通过强制MyScene
类等待几秒钟,然后使用方法检索(如public String getMatched()
在Browser
(未列出)类中或通过通知MyScene
类变量已更新。但我不知道,怎么做。有没有人有什么建议?
MyScene.java:
package mypackage;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.concurrent.Task;
public class MyScene extends Application {
private Scene scene;
private static String address = "https://www.google.com";
@Override public void start(Stage stage) {
// create the scene
stage.setTitle("Web View");
Browser myBrowser = new Browser(address);
scene = new Scene(myBrowser,750,500);
stage.setResizable(false);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args){
launch();
}
}
浏览器.java:
package mypackage;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker.State;
import javafx.geometry.HPos;
import javafx.geometry.VPos;
import javafx.scene.Node;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
class Browser extends Region {
private String matched;
final WebView browser = new WebView();
final WebEngine webEngine = browser.getEngine();
public Browser(String loadAddress) {
String myAddress = loadAddress;
//apply the styles
getStyleClass().add("browser");
// load the web page
webEngine.load(myAddress);
//add the web view to the scene
getChildren().add(browser);
webEngine.getLoadWorker().stateProperty().addListener(
new ChangeListener<State>() {
public void changed(ObservableValue ov, State oldState, State newState) {
if (newState == State.SUCCEEDED) {
Pattern fbPattern = Pattern.compile(" <title id=\"([...]+)\">");
NodeList lst = webEngine.getDocument().getElementsByTagName("script");
if (lst != null && lst.getLength() > 0) {
for (int i = 0; i < lst.getLength(); i++) {
if (lst.item(i).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
Element el = (Element) lst.item(i);
Matcher fbMatcher = fbPattern.matcher(el.getTextContent());
if (fbMatcher.find()) {
matched = fbMatcher.group(1);
}
}
}
}
}
}
});
}
private Node createSpacer() {
Region spacer = new Region();
HBox.setHgrow(spacer, Priority.ALWAYS);
return spacer;
}
@Override protected void layoutChildren() {
double w = getWidth();
double h = getHeight();
layoutInArea(browser,0,0,w,h,0, HPos.CENTER, VPos.CENTER);
}
@Override protected double computePrefWidth(double height) {
return 750;
}
@Override protected double computePrefHeight(double width) {
return 500;
}
}