Search code examples
javaswingjscrollpanejtextpanecaret

JTextpane set caret position without changing scrollPane


I have Jtextpane added to scroll pane and i use the following code,

textPanel.setCaretPosition(5);
JScrollBar sb = scroll.getVerticalScrollBar();
sb.setValue( sb.getMaximum());

The contents of jtextpane is simple 10 "\n" characters. The above piece of code i use to set caret position at some place keeping scroll bar at bottom. if i remove setCaretPosition i can able to set scroll position at bottom but with that code its always going to top.

Note : caret property is ALWAYS_UPDATE .

Is it possible to achieve this?

Please help


Solution

  • You can use the methods

    public CaretListener[] getCaretListeners()
    public void addCaretListener(CaretListener listener)
    public void removeCaretListener(CaretListener listener)
    

    Before setting caret to position get all the caret listeners, remove them, set your caret position and readd them back.