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 9202121
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T23:10:52+00:00 2026-06-17T23:10:52+00:00

So, i have a situation where, a scrollbar needs to scroll automatically when meets

  • 0

So, i have a situation where, a scrollbar needs to scroll automatically when meets a certain logical situation.

In my case, i have few lines written on JTextPane, and i am highlighting the words.So, when the point is reached,where the text is not visible,the scroll bar should automatically scroll down.

Few screen shots will make it clear:

enter image description here

As you can see, now the screen is filled with the highlited text.So at this point the scrollbar should move down, something like this:

enter image description here

I am blank which logic to use beacuse:

1) The number of lines of .txt file will change.

2)The timing of highlighting of words may change.

Any logic to overcome this situation?

  • 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-17T23:10:54+00:00Added an answer on June 17, 2026 at 11:10 pm

    You can simply use the JTextComponent.modelToView(int) method to find out the location of a given position in the text and then use scrollRectToVisible.

    Small demo example:

    import java.awt.Color;
    import java.awt.Rectangle;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.lang.reflect.InvocationTargetException;
    
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextPane;
    import javax.swing.SwingUtilities;
    import javax.swing.Timer;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.DefaultStyledDocument;
    import javax.swing.text.SimpleAttributeSet;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.StyledDocument;
    
    public class TestKaraoke {
    
        private JFrame frame;
        private Timer timer;
        private StyledDocument doc;
        private JTextPane textpane;
    
        private int index = 0;
    
        public void startColoring() {
            ActionListener actionListener = new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent actionEvent) {
                    highlightNextWord();
                }
            };
            timer = new Timer(50, actionListener);
            timer.setInitialDelay(0);
            timer.start();
        }
    
        protected void highlightNextWord() {
            boolean reachedEnd = false;
            SimpleAttributeSet sas = new SimpleAttributeSet();
            StyleConstants.setForeground(sas, Color.RED);
            int end = textpane.getText().indexOf(' ', index + 1);
            if (end == -1) {
                end = textpane.getDocument().getLength();
                reachedEnd = true;
            }
            ((StyledDocument) textpane.getDocument()).setCharacterAttributes(index, end - index, sas, true);
            try {
                Rectangle modelToView = textpane.modelToView(end);
                textpane.scrollRectToVisible(modelToView);
            } catch (BadLocationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            index = end;
            if (reachedEnd) {
                timer.stop();
            }
        }
    
        public void initUI() {
            frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            doc = new DefaultStyledDocument();
            textpane = new JTextPane(doc);
            textpane.setText(TEXT);
            frame.add(new JScrollPane(textpane));
            frame.setSize(300, 300);
            frame.setVisible(true);
        }
    
        public static void main(String args[]) throws InterruptedException, InvocationTargetException {
            SwingUtilities.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    TestKaraoke karaoke = new TestKaraoke();
                    karaoke.initUI();
                    karaoke.startColoring();
                }
            });
        }
    
        private static final String TEXT = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras at vulputate nisi. Phasellus varius massa turpis, eget commodo quam. Vivamus vel varius neque. Cras vestibulum aliquet arcu, sed fringilla elit pretium vel. Nunc nibh tellus, dignissim vitae scelerisque vulputate, hendrerit eu arcu. Aenean tincidunt, sem ut sollicitudin blandit, lorem nulla placerat turpis, condimentum mollis felis risus sed leo. Proin a nisi tristique nisi convallis faucibus vitae ut nulla. Sed aliquam, dolor id lobortis pellentesque, nisl mi sagittis mi, sed bibendum arcu arcu vitae odio. Nunc dapibus, tellus non convallis convallis, augue ipsum lobortis massa, sit amet porta lectus augue non lorem. Nam hendrerit vestibulum risus quis accumsan. Mauris ac eros ipsum. Curabitur et odio nulla, sed egestas lorem. Integer sed pretium diam. Vivamus ullamcorper tortor eu ante iaculis non ullamcorper ante consectetur. Sed sit amet lacus enim, et faucibus dui. Vestibulum tempor luctus lorem non lacinia.\r\n"
                + "\r\n"
                + "Vivamus euismod interdum iaculis. Cras diam odio, venenatis sed hendrerit eget, hendrerit ac dolor. Integer vulputate, lorem et auctor hendrerit, elit elit mattis felis, ut mollis velit est quis quam. Vestibulum vel eros mauris, at ultrices tellus. Proin ac lectus lectus. Morbi vehicula ullamcorper tortor a adipiscing. Ut turpis elit, consectetur id vehicula sed, tempor quis augue. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Maecenas est enim, pulvinar id aliquam convallis, vehicula non enim.\r\n"
                + "\r\n"
                + "Praesent porttitor eros eros, sed mattis ante. Maecenas lobortis condimentum ante, ac condimentum nibh malesuada nec. Mauris luctus facilisis magna non elementum. Vestibulum nibh ante, fringilla ut hendrerit ac, dignissim tempus felis. Duis odio orci, ultrices quis blandit vel, feugiat eu orci. Donec sit amet cursus nulla. Vivamus pharetra posuere tellus, venenatis sollicitudin velit dignissim et. Fusce commodo enim non dui malesuada at malesuada neque semper. Sed dui lacus, auctor vel viverra in, molestie sed leo.\r\n"
                + "\r\n"
                + "Suspendisse potenti. In ipsum mi, scelerisque pellentesque rutrum quis, pretium interdum velit. Suspendisse euismod, velit vel tristique semper, odio mauris gravida eros, mollis dictum massa justo ullamcorper tortor. Donec ut dolor felis. Duis dapibus condimentum orci, vel tempor orci egestas ac. Proin eleifend facilisis ipsum, sit amet volutpat neque suscipit ut. Phasellus lobortis tempor nulla, a tristique neque vulputate in. Integer arcu elit, pharetra in ullamcorper in, semper eu libero. Nunc ac felis iaculis eros placerat viverra. Praesent in nibh nibh, vel elementum nisi. Morbi posuere elementum est, at vulputate est interdum in.\r\n"
                + "\r\n"
                + "Proin nisi libero, rhoncus eget bibendum et, aliquet eget nisi. Sed bibendum, ante eu adipiscing mattis, turpis lacus mollis odio, id iaculis mauris felis eu justo. In hac habitasse platea dictumst. In hac habitasse platea dictumst. Duis lobortis placerat odio, sed commodo sapien vulputate volutpat. Vestibulum pretium faucibus justo, ac rutrum risus vulputate ut. Nulla interdum malesuada tortor in cursus. Mauris libero neque, sagittis ornare tristique a, pretium sed eros. Nulla consectetur feugiat nunc eget tincidunt. Integer luctus, mi non euismod congue, nibh risus posuere magna, eget mattis orci elit ut sapien. Nam eu imperdiet sapien. Etiam non commodo turpis. ";
    }
    

    (For the demo purposes, I made the screen quite small and the reader must be furiously good ;-))

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have situation where my Java class needs to create a ton of certain
I have situation where a single model needs to have three foreign ids. This
i have situation like this: class IData { virtual void get() = 0; virtual
I have situation, where running a query that filters by an indexed column in
I have situation in which I read a record from a database. And if
I have situation where I need to change the order of the columns/adding new
I have situation where a user can manipulate a large set of data (presented
I have situation like this: user submits form with action='/pay' in '/pay' I have
We have situation where say we have four engineers that are working on software
Pseudo-situation: have a class (let's say BackgroundMagic ), and it has Start() and Stop()

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.