gpt4 book ai didi

JavaFX - 如何将字符串从 'webEngine createWebEngine(Stage stage)' 显示到其他类中的 Pane

转载 作者:太空宇宙 更新时间:2023-11-04 10:47:35 26 4
gpt4 key购买 nike

我正在尝试将下面代码中的字符串显示到其他类中的 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);

关于JavaFX - 如何将字符串从 'webEngine createWebEngine(Stage stage)' 显示到其他类中的 Pane ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48222034/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com