Search code examples
javaswingjscrollpanejscrollbaradjustment

JScrollPane Set Scroll Position


I have following code snippet

query_area = new JTextArea("");
query_scroll_pane = new JScrollPane(query_area);
query_scroll_pane.setSize(1000,80);
query_scroll_pane.setLocation(10,10);
query_panel.add(query_scroll_pane);

which adds my textarea to scrollpane. Now in a method i dynamically set text for the textarea as

sf.query_area.setText("Query "+(sf.query_counter)+sf.query_store[sf.query_counter]);
System.out.println("Position: "+sf.query_scroll_pane.getHorizontalScrollBar().getValue());

Now my query is when longer text is displayed, scrollbars appear but system.out.println prints position of scrollbar as 0 and not some increased value.

Why so ??


Solution

  • The only reason I can think of is because the view port position hasn't changed.

    The first thing that comes to mind, is the view port may not have yet reacted to a change in position from the text begin set, so dumping the result immediately after you've set the text is reflecting the current state of the scroll bar (which has not yet begin updated)

    You could try

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            System.out.println("Position: "+sf.query_scroll_pane.getHorizontalScrollBar().getValue());        
        }
    });
    

    instead and see if that prints out a more up-to-date value

    Alternativly, you could add a AdjustmentListener to the scroll bar, which will notify when changes occur JScrollBar#addAdjustmentListener