我正在尝试将以下代码中的String显示到其他类中的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;
所以,代码中有String'xml'。 当然,我可以在控制台中打印。但我想在另一个类的窗格中显示。我尝试使用Text对象来保存带有setText(xml)和getText()的String,但它对我不起作用,或者我以错误的方式使用。
你对此有什么想法吗? 感谢。
答案 0 :(得分:0)
如果这是在某个类中,比如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);