您可以JTextPane
在更新其内容之后但在创建之前将您的插入符号位置简单地设置为 0 JScrollPane
。这将强制JScrollPane
立即显示文本的开头,而无需向后滚动。
只需执行以下操作:
JTextPane textPane = new JTextPane ();
textPane.setText ( "Some long text here..." );
textPane.setCaretPosition ( 0 );
JScrollPane scrollPane = new JScrollPane ( textPane );
如果您已经有文本 - 只需在 EDT 中同时进行更新和插入符号位置切换:
public static void main ( String[] args ) throws InterruptedException
{
final JFrame frame = new JFrame ();
final JTextPane textPane = new JTextPane ();
frame.add ( new JScrollPane ( textPane ) );
frame.setSize ( 400, 300 );
frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
frame.setLocationRelativeTo ( null );
frame.setVisible ( true );
Thread.sleep ( 2000 );
SwingUtilities.invokeLater ( new Runnable ()
{
public void run ()
{
textPane.setText ( "line\nline\nline\nline\nline\nline\nline\nline" +
"\nline\nline\nline\nline\nline\nline\nline\nline\nline" +
"\nline\nline\nline\nline\nline\nline\nline\nline\nline" +
"\nline\nline\nline\nline\nline\nline\nline\nline\nline" );
textPane.setCaretPosition ( 0 );
}
} );
Thread.sleep ( 2000 );
SwingUtilities.invokeLater ( new Runnable ()
{
public void run ()
{
textPane.setText ( "line2\nline\nline\nline\nline\nline\nline\nline" +
"\nline\nline\nline\nline\nline\nline\nline\nline\nline" +
"\nline\nline\nline\nline\nline\nline\nline\nline\nline" +
"\nline\nline\nline\nline\nline\nline\nline\nline\nline" );
textPane.setCaretPosition ( 0 );
}
} );
}
但我同意这不是最好的解决方案。我想没有简单的方法可以在其内容更改时强制 textpane 插入符号为 0。