Search code examples
javaswingjframejscrollpanejtextcomponent

Scroll to a specific part of a JFrame


Using Cobra, I have a void function which will scroll to a given node of a dom tree or a given pixel of the htmlpane. When I use JFrame.setContentPane() function to set the htmlpane as the container, and I use the scroll() function to scroll the specefic point, it's not working.

Here is the code:

HtmlRendererContext rendererContext = (HtmlRendererContext) new  LocalHtmlRendererContext(htmlPanel, uAgent);
DocumentBuilderImpl builder = new DocumentBuilderImpl(uAgent, rendererContext);
Document document = builder.parse(url);
JFrame frame = new JFrame();
htmlPanel.scroll(500, 300);
//frame.getContentPane().add(htmlPanel);
frame.setContentPane(htmlPanel);

and if you see the following code:

frame.setContentPane(htmlPanel.scroll(500, 300));

it says:

no void function allowed here.


Solution

  • I am not familiar with the Cobra API you are using but in most cases GUI components have to lay themselves out before you can scroll. This is because before you add a component to a container it does not know what size it will be. Try delaying the scroll and see if it helps:

    frame.setContentPane(htmlPanel);
    frame.setVisible(true);
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            htmlPanel.scroll(500, 300);
        }
    });