Java Swing - Using JScrollPane and Having it scroll back to top

前端 未结 7 954
[愿得一人]
[愿得一人] 2020-12-09 00:52

I\'m using JScrollPane to allow scrolling in a JFrame that has a text component that\'s serving as a text editor. What I want to do, after setting the text in this editor,

相关标签:
7条回答
  • 2020-12-09 00:57

    You can try this:

     scrollPane.getViewport().setViewPosition(new Point(0,0));
    

    According to the JavaDocs setViewPosition() behaves like this:

    Sets the view coordinates that appear in the upper left hand corner of the viewport, does nothing if there's no view.

    0 讨论(0)
  • 2020-12-09 01:03

    Just in case you are not using a text component take a look at the thread posted here.... Setting Scroll Bar on a JScrollPane

    Their solution is to spin off a thread via invokeLater

    final JScrollPane scroll = new JScrollPane(text);
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
       public void run() { 
           scroll.getVerticalScrollBar().setValue(0);
       }
    });
    
    0 讨论(0)
  • 2020-12-09 01:03

    This will make the work:

    DefaultCaret caret = (DefaultCaret) textArea.getCaret();
    caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
    
    0 讨论(0)
  • 2020-12-09 01:09

    Calling setCaretPosition(0) on your text component will cause it to scroll to the top.

    0 讨论(0)
  • 2020-12-09 01:09

    You can use the method setCaretPosition(0) just after setText(String t) of your text component.

    0 讨论(0)
  • 2020-12-09 01:12

    Here's how:

    textArea.setSelectionStart(0);
    textArea.setSelectionEnd(0); 
    
    0 讨论(0)
提交回复
热议问题