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

  • Home
  • SEARCH
  • 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 537451
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T09:55:42+00:00 2026-05-13T09:55:42+00:00

I have a JScrollPane with a JTextArea set as its view port. I update

  • 0

I have a JScrollPane with a JTextArea set as its view port.

I update the (multi line) text shown on the JTextArea continously about once a second. Each time the text updates, JScrollPane goes all the way to the bottom of the text.

Instead, I’d like to figure out the line number that is currently shown as the first line in the original text, and have that line be the first line shown when the text has been updated (or if the new text doesn’t have that many lines, then scroll all the way to the bottom).

My first attempt of doing this was to get the current caret position, figure the line based on that, and then set the text area to show that line:

    int currentPos = textArea.getCaretPosition();
    int currentLine = 0;
    try {
        for(int i = 0; i < textArea.getLineCount(); i++) {
            if((currentPos >= textArea.getLineStartOffset(i)) && (currentPos < gameStateTextArea.getLineEndOffset(i))) {
                currentLine = i;
                break;
            }
        }
    } catch(Exception e) { }

    textArea.setText(text);

    int newLine = Math.min(currentLine, textArea.getLineCount());
    int newOffset = 0;
    try {
        newOffset = textArea.getLineStartOffset(newLine);
    } catch(Exception e) { }

    textArea.setCaretPosition(newOffset);

This was almost acceptable for my needs, but requires the user to click inside the text area to change the caret position, so that the scrolling will maintain state (which isn’t nice).

How would I do this using the (vertical) scroll position instead ?

  • 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-05-13T09:55:42+00:00Added an answer on May 13, 2026 at 9:55 am

    This is pieced together, untested, from the API documentation:

    • use getViewport() on your JScrollPane to get a hold of the viewport.
    • use Viewport.getViewPosition() to get the top-left coordinates. These are absolute, not a percentage of scrolled text.
    • use Viewport.addChangeListener() to be notified when the top-left position changes (among other things). You may want to create a mechanism to distinguish user changes from changes your program makes, of course.
    • use Viewport.setViewPosition() to set the top-left position to where it was before the disturbance.

    Update:

    • To stop JTextArea from scrolling, you may want to override its getScrollableTracksViewport{Height|Width}() methods to return false.

    Update 2:

    The following code does what you want. It’s amazing how much trouble I had to go to to get it to work:

    • apparently the setViewPosition has to be postponed using invokeLater because if it’s done too early the text update will come after it and nullify its effect.
    • also, for some weird reason perhaps having to do with concurrency, I had to pass the correct value to my Runnable class in its constructor. I had been using the “global” instance of orig and that kept setting my position to 0,0.

    public class Sami extends JFrame implements ActionListener {
    
       public static void main(String[] args) {
          (new Sami()).setVisible(true);
       }
    
       private JTextArea textArea;
       private JScrollPane scrollPane;
       private JButton moreTextButton = new JButton("More text!");
       private StringBuffer text = new StringBuffer("0 Silly random text.\n");
       private Point orig = new Point(0, 0);
    
       public Sami() {
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          getContentPane().setLayout(new BorderLayout());
          this.textArea = new JTextArea() {
             @Override
             public boolean getScrollableTracksViewportHeight() {
                return false;
             }
             @Override
             public boolean getScrollableTracksViewportWidth() {
                return false;
             }
          };
          this.scrollPane = new JScrollPane(this.textArea);
          getContentPane().add(this.scrollPane, BorderLayout.CENTER);
          this.moreTextButton.addActionListener(this);
          getContentPane().add(this.moreTextButton, BorderLayout.SOUTH);
          setSize(400, 300);
       }
    
       @Override
       public void actionPerformed(ActionEvent arg0) {
          int lineCount = this.text.toString().split("[\\r\\n]").length;
          this.text.append(lineCount + "The quick brown fox jumped over the lazy dog.\n");
          Point orig = this.scrollPane.getViewport().getViewPosition();
          // System.out.println("Orig: " + orig);
          this.textArea.setText(text.toString());
          SwingUtilities.invokeLater(new LaterUpdater(orig));
       }
    
       class LaterUpdater implements Runnable {
          private Point o;
          public LaterUpdater(Point o) {
             this.o = o;
          }
          public void run() {
             // System.out.println("Set to: " + o);
             Sami.this.scrollPane.getViewport().setViewPosition(o);
          }
       } 
    
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 280k
  • Answers 280k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer If you have a lot of those small interface tweaks,… May 13, 2026 at 3:39 pm
  • Editorial Team
    Editorial Team added an answer Why do you need this in the bootloader ? You… May 13, 2026 at 3:39 pm
  • Editorial Team
    Editorial Team added an answer Install a global hook onto the mouse-move event and check… May 13, 2026 at 3:39 pm

Related Questions

I'm using a JTextArea to display a long text JTextArea _definition = new JTextArea(5,
I recently purchased the book Filthy Rich Clients and i found it really useful
I have an issue where Swing (in Java 1.6, Windows) doesn't seem to trigger
I am currently working on a SWING frame with a JScrollPane (including a JComponent),
I have a JTable with a custom TableModel called DataTableModel . I initialized the

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

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.