我正在尝试将下面代码中的字符串显示到其他类中的 Pane 。
public WebEngine helloWebEngine(Stage stage) {
WebView wv = getWebView();
webEngine = wv.getEngine();
webEngine.getLoadWorker().stateProperty().addListener(new ChangeListener<State>() {
@Override
public void changed(ObservableValue<? extends State> ov, State oldState, State newState) {
if (newState == Worker.State.RUNNING) {
stage.setTitle(webEngine.getLocation());
try {
TransformerFactory transformerFactory = TransformerFactory
.newInstance();
Transformer transformer = transformerFactory.newTransformer();
StringWriter stringWriter = new StringWriter();
transformer.transform(new DOMSource(webEngine.getDocument()),
new StreamResult(stringWriter));
String xml = stringWriter.getBuffer().toString();
System.out.println(xml);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
return webEngine;
所以,代码中有字符串“xml”。当然,我可以在控制台中打印。但我想在另一个类的 Pane 上显示。我尝试使用 Text 对象通过 setText(xml) 和 getText() 来保存 String,但它对我不起作用,或者我使用了错误的方式。
你对此有什么想法吗?谢谢。
如果这是在某个类中,例如 WebViewTransformer
(您可能可以选择更好的名称),请向该类添加一个 StringProperty
并从处理程序中设置它:
public class WebViewTransformer {
private final StringProperty xml = new SimpleStringProperty();
public StringProperty xmlProperty() {
return xml ;
}
public final String getXml() {
return xmlProperty().get();
}
public final void setXml(String xml) {
xmlProperty().set(xml);
}
// not really sure why this takes a stage as parameter....
public WebEngine helloWebEngine(Stage stage) {
WebView wv = getWebView();
webEngine = wv.getEngine();
webEngine.getLoadWorker().stateProperty().addListener(new ChangeListener<State>() {
@Override
public void changed(ObservableValue<? extends State> ov, State oldState, State newState) {
if (newState == Worker.State.RUNNING) {
stage.setTitle(webEngine.getLocation());
try {
TransformerFactory transformerFactory = TransformerFactory
.newInstance();
Transformer transformer = transformerFactory.newTransformer();
StringWriter stringWriter = new StringWriter();
transformer.transform(new DOMSource(webEngine.getDocument()),
new StreamResult(stringWriter));
String xml = stringWriter.getBuffer().toString();
setXml(xml);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
return webEngine;
}
}
现在你只需要做
WebViewTransformer transformer = new WebViewTransformer() ;
transformer.xmlProperty().addListener((obs, oldXML, newXML) -> {
// display newXML wherever you need...
});
WebEngine engine = transformer.helloWebEngine(primaryStage);
我是一名优秀的程序员,十分优秀!