Note that there are some explanatory texts on larger screens.

plurals
  1. POJTextArea in JScrollPane, view coordinate translation
    primarykey
    data
    text
    <p>I'm trying to translate between view and viewport coordinates. But the JViewport/JScrollpane doesn't seem to work as documented. <code>JViewport.toViewCoordinates()</code> thinks the view is always at the top left of the component, even though that's clearly not the case.</p> <pre><code>String text = "blahblahblah\nblahblah\nblah"; JFrame frame = new JFrame("title"); JTextArea textArea = new JTextArea(text, 1, 30); // shows only one line frame.add(new JScrollPane(textArea)); frame.pack(); frame.setVisible(true); textArea.setCaretPosition(text.length()); // now showing the last line JViewport viewport = ((JViewport)textArea.getParent()); viewport.getViewRect(); // returns java.awt.Rectangle[x=0,y=0,width=330,height=16] viewport.getViewPosition(); // returns java.awt.Point[x=0,y=0] viewport.toViewCoordinates(new Point(0,0)); // returns java.awt.Point[x=0,y=0] </code></pre> <p>The above is contrived example. My real <code>JTextArea</code> is larger than one line. I don't need JTextArea "model" coordinate (the offset in the text). I need genuine 2d coordinates.</p> <p>The view position shouldn't be (0,0), as the first visible character in the viewport is actually in the 3rd line of the JTextArea.</p> <p>Any other suggestions on how I can translate between view and component coordinates when using JScrollPane?</p> <p>--- added ---</p> <p>This also fails.</p> <pre><code>SwingUtilities.convertPoint(viewport,0,0, textArea); (java.awt.Point) java.awt.Point[x=0,y=0] </code></pre> <p>--- added ---</p> <p>Here is the final working version, based on the answer I received. it shows <code>java.awt.Point[x=0,y=32]</code> which is what I expected.</p> <pre><code>@Test public void test() throws InterruptedException { String text = "blahblahblah\nblahblah\nblah"; JFrame frame = new JFrame("title"); JTextArea textArea = new JTextArea(text, 1, 30); frame.add(new JScrollPane(textArea)); frame.pack(); frame.setVisible(true); textArea.setCaretPosition(text.length()); final JViewport viewport = ((JViewport)textArea.getParent()); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { System.out.println(viewport.getViewPosition()); } }); Thread.sleep(1000); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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