Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8392213
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T19:27:43+00:00 2026-06-09T19:27:43+00:00

I can’t figure out how JEditorPane.scrollToReference() is meant to be used with a dynamically-generated

  • 0

I can’t figure out how JEditorPane.scrollToReference() is meant to be used with a dynamically-generated HTML page. I’d like to open a dialog box with a JEditorPane that is scrolled to an anchor of my choosing. No matter how I approach the problem, the view is always scrolled at the bottom of the page.

As an ugly workaround, I currently parse the entire HTML document for anchor tags, save their offsets in a Map<String, Integer>, and then I call:

editorPane.setCaretPosition(anchorMap.get("anchor-name"));

…which doesn’t even produce an attractive result, because the caret position within the visible rectangle is seemingly unpredictable, and is rarely at the top of the window. I’m looking for a more browser-like behavior where the anchored text appears at the top of the visible area.

Below is a screenshot of what happens with my awkward workaround (there is an anchor on “header 6”), without having touched the scroll bar:

screenshot

I think I’m missing something but I can’t figure out what exactly.

Source of my current workaround:

import javax.swing.*;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.*;
import javax.swing.text.html.HTMLEditorKit.*;
import javax.swing.text.html.parser.*;
import java.io.*;
import java.awt.*;
import java.util.HashMap;

public class AnchorTest
{
    public static void main(String[] args)
    {
        final String html = generateLongPage();
        final HashMap<String, Integer> anchors = anchorPositions(html);

        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                JEditorPane editor  = new JEditorPane("text/html", html);
                JScrollPane scroller= new JScrollPane(editor);

                scroller.setPreferredSize(new Dimension(400, 250));

                //editor.scrollToReference("anchor6");  // doesn't work...
                editor.setCaretPosition(anchors.get("anchor6")); //sorta works

                JOptionPane.showMessageDialog(new JPanel(), scroller, "",
                        JOptionPane.PLAIN_MESSAGE);
            }});
    }

    public static HashMap<String, Integer> anchorPositions(String html)
    {
        final HashMap<String, Integer> map = new HashMap<String, Integer>();

        Reader reader = new StringReader(html);
        HTMLEditorKit.Parser parser = new ParserDelegator();

        try
        {
            ParserCallback cb = new ParserCallback()
            {
                public void handleStartTag(HTML.Tag t,
                                           MutableAttributeSet a,
                                           int pos)
                {
                    if (t == HTML.Tag.A) {
                        String name = 
                            (String)a.getAttribute(HTML.Attribute.NAME);
                        map.put(name, pos);
                    }
                }
            };

            parser.parse(reader, cb, true);
        }
        catch (IOException ignore) {}

        return map;
    }


    public static String generateLongPage()
    {
        StringBuilder sb = new StringBuilder(
                "<html><head><title>hello</title></head><body>\n");

        for (int i = 0; i < 10; i++) {
            sb.append(String.format(
                    "<h1><a name='anchor%d'>header %d</a></h1>\n<p>", i, i));

            for (int j = 0; j < 100; j++) {
                sb.append("blah ");
            }
            sb.append("</p>\n\n");
        }

        return sb.append("</body></html>").toString();
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T19:27:44+00:00Added an answer on June 9, 2026 at 7:27 pm

    The problem is probably because the pane is not visible yet or not laid out yet when scrollToReference is executed, so its size cannot be determined.

    The implementation of scrollToReference has the following block:

    Rectangle r = modelToView(iter.getStartOffset());
    if (r != null) {
       ...
       scrollRectToVisible(r);
    }
    

    In the posted example the rectangle is null for anchor6, since the view is not yet visible or its size is not positive.

    Try this dirty fix to delay scrolling:

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            editor.scrollToReference("anchor6");
        }
    });
    JOptionPane.showMessageDialog(new JPanel(), scroller, "",
            JOptionPane.PLAIN_MESSAGE);
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm new to using the Perl treebuilder module for HTML parsing and can't figure
Can't figure out how to do this in a pretty way : I have
Can't seem to figure out what's wrong with the simple getJSON call below. It's
Can I run this in a Windows command prompt like I can run it
Can't work out a way to make an array of buttons in android. This
Can anyone tell me how I can display a status message like 12 seconds
I would like my Web page http://www.gmarks.org/math_in_e-mail.txt on my Apache 2.2.14 server to display
Can we change the HTML or its attributes of the selected part of the
Can you pls explain? I looked at this site for the data http://www.d.umn.edu/~gshute/java/statements.html while
Can anyone let me know how can we change the value of kendo combobox

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.