gpt4 book ai didi

java - Swing HTMLDocument 不包含所有 HTML 元素?

转载 作者:行者123 更新时间:2023-11-30 02:54:41 26 4
gpt4 key购买 nike

我有一个 swing 应用程序,其中包含一个显示 HTML 文件的对话框。我这样做是这样的:

URL url = getClass().getResource("/resources/EULA.html");

JDialog eulaDialog = new JDialog();
JEditorPane eulaEP = new JEditorPane();
try {
eulaEP.setPage(url);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

JScrollPane scrollPane = new JScrollPane(eulaEP);
eulaDialog.getContentPane().add(scrollPane);
eulaDialog.setBounds(400, 200, 700, 600);
eulaDialog.setVisible(true);

这正如我预期的那样工作。它正确显示 HTML 文件。

我现在尝试在文档中查找一个元素,因此我这样做:

HTMLDocument htm = (HTMLDocument) eulaEP.getDocument();
Element el = htm.getElement("unique_id");

但这会返回 null(即使该元素显示在对话框中)。

我决定通过执行以下操作来检查文档中包含哪些元素:

for (ElementIterator iterator = new ElementIterator(htm); iterator.next() != null;)

然而,这仅返回 4 个元素; html、正文、p 和内容。我的 HTML 文件还有很多内容(内容是什么?)我做错了什么?

为了澄清,HTML 包含一个按钮,我想向此按钮添加一个 ActionListener,以便我可以在我的 java 代码中捕获对其的单击。

最佳答案

我的猜测是您在文档完全加载之前正在阅读该文档。 doocumentation for JEditorPane.setPage这方面的信息非常丰富:

This may load either synchronously or asynchronously depending upon the document returned by the EditorKit. … If the document is loaded asynchronously, the document will be installed into the editor immediately using a call to setDocument which will fire a document property change event, then a thread will be created which will begin doing the actual loading. In this case, the page property change event will not be fired by the call to this method directly, but rather will be fired when the thread doing the loading has finished. It will also be fired on the event-dispatch thread.

因此,在文档加载之前,您不应该查看该文档。例如:

JEditorPane eulaEP = new JEditorPane();
eulaEP.addPropertyChangeListener("page", e -> {
HTMLDocument htm = (HTMLDocument) eulaEP.getDocument();
Element el = htm.getElement("unique_id");
// ...
});

try {
eulaEP.setPage(url);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

关于java - Swing HTMLDocument 不包含所有 HTML 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37614945/

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