2

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 ??

mKorbel
  • 109,525
  • 20
  • 134
  • 319
aditya parikh
  • 595
  • 4
  • 11
  • 30
  • Horizontal or Vertical scrollBar position? And where is the slider located on the JScrollBar? Also, your question title is about *set* scroll position, when you really appear to be asking about *getting* the scroll position. Which is it? – Hovercraft Full Of Eels Nov 03 '12 at 20:10
  • I guess that I wrote my comment above in invisible ink? – Hovercraft Full Of Eels Nov 03 '12 at 20:49
  • My question was not that unclear as your comment made it sound. it was clear enough and also got answer from one of the comments below. Thanks anyway – aditya parikh Nov 03 '12 at 21:01

2 Answers2

4

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

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Ya MadProgrammer. the above code snippet is printing the latest value. so is there any dumping method or using above codesnippet is the only option ?? – aditya parikh Nov 03 '12 at 20:36
  • Depends on what you want to achieve. If you want to know when the value changes, you need to attach a AdjustmentListener to the scroll bar, which will notify you automatically when the values change – MadProgrammer Nov 03 '12 at 20:44
1

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.

use

query_area = new JTextArea();
DefaultCaret caret = (DefaultCaret) query_area.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
mKorbel
  • 109,525
  • 20
  • 134
  • 319