我是Java和JavaFX的新手。我不知道如何将变量matched
从实现Web引擎的(Browser
)类传递回应用程序(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();
}
}
Browser.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;
}
}