Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The problem is that the method to get the viewPosition() executes before the viewport has actually been scrolled. This is because sometimes Swing adds code to the end of the event thread for later processing.</p> <p>Usually this problem can be solved by wrapping your code in a SwingUtilities.invokeLater() so the code is executed after Swing has done all its processing. However in the simple demo below I found I needed to add two invokeLater() methods. I'm not sure why. </p> <p>Move the caret up/down and you will see the view position change. The second value will contain the correct position:</p> <pre><code>import java.awt.*; import javax.swing.*; import javax.swing.event.*; public class Test5 { public static void createAndShowGUI() { String text = "one\ntwo\nthree\nfour\nfive"; JFrame frame = new JFrame("title"); JTextArea textArea = new JTextArea(text, 1, 30); // shows only one line JScrollPane scrollPane = new JScrollPane( textArea ); frame.add(scrollPane); frame.pack(); frame.setVisible(true); final JViewport viewport = scrollPane.getViewport(); textArea.addCaretListener( new CaretListener() { public void caretUpdate(CaretEvent e) { SwingUtilities.invokeLater(new Runnable() { public void run() { System.out.println("First : " + viewport.getViewPosition() ); SwingUtilities.invokeLater(new Runnable() { public void run() { System.out.println("Second: " + viewport.getViewPosition() ); } }); } }); } }); textArea.setCaretPosition(text.length()); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload