问题描述
我正在渲染网页,并尝试滚动到其中的某个位置.但是,滚动不起作用.
I am rendering a webpage and trying to scroll to a location within it. However, the scrolling doesn't work.
这是我的代码...
import org.lobobrowser.html.*;
import org.lobobrowser.html.gui.HtmlPanel;
import org.lobobrowser.html.parser.*;
import org.lobobrowser.html.test.*;
import org.w3c.dom.*;
import org.xml.sax.*;
public class finall {
Node goTo;
public void show(URL url,Node theFinalNode) throws MalformedURLException, IOException, SAXException {
goTo = theFinalNode;
String uri=url.toString();
URLConnection connection = url.openConnection();
InputStream in = connection.getInputStream();
Reader reader = new InputStreamReader(in);
InputSource is = new InputSourceImpl(reader, uri);
UserAgentContext uAgent=new SimpleUserAgentContext();
final HtmlPanel htmlPanel = new HtmlPanel();
HtmlRendererContext rendererContext = (HtmlRendererContext) new LocalHtmlRendererContext(htmlPanel, uAgent);
DocumentBuilderImpl builder = new DocumentBuilderImpl(uAgent, rendererContext);
Document document = builder.parse(is);
JFrame frame = new JFrame();
frame.getContentPane().add(htmlPanel);
htmlPanel.setDocument(document, rendererContext);
frame.setSize(300, 450);
frame.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
htmlPanel.scrollTo(goTo);
}
});
}
有人可以帮我理解为什么滚动不起作用的原因.
Could someone please help me understand why the scrolling doesn't work.
推荐答案
在我看来,要传递给show方法的Node不在HtmlPanel正在查看的文档中.在您的代码中,您可以使用以下方式构建文档:
It looks to me as if the Node that you are passing in to the show method is not in the document being viewed by the HtmlPanel. In your code you build the document using:
Document document = builder.parse(is);
这将创建一个新文档以及与之关联的许多新节点.参数theFinalNode将不属于该文档,因为它是在创建文档之前创建的.您将需要通过调用文档对象上的方法或使用类似XPath的方法从新文档中提取所需的Node:
This will create a new document and a lot of new Nodes associated with it. The parameter theFinalNode will not be part of this document as it was created before the document was created. You will need to extract the Node you want from your new document by calling methods on the document object, or by using something like XPath:
http://www.roseindia.net/tutorials/xPath/java- xpath.shtml
一旦您有一个Node实际上是所查看文档的一部分,那么scrollTo方法就应该起作用.
Once you have a Node that is actually part of the viewed document then the scrollTo method should work.
这篇关于滚动到网页的另一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!