Serhiy
Serhiy

Reputation: 4141

Customization of scroll+caret behaviour in JTextArea+JScrollPane

I have a problem implementing the behavior I want in mentioned components. The behavior I want is:
1) By default, when new content is appended to JTextArea, it's auto scrolling to the last inserted line. This one I managed to do with:
DefaultCaret caret = (DefaultCaret)textArea.getCaret(); caret.setUpdatePolicy(DefaultCaret.NEVER_ALWAYS);
2) When user either with mouse or with keyboard moving scrollbar, auto scrolling should be disabled and the text to which user has scrolled is displayed (here I tried to implement AdjustmentListener which on action was setting DefaultCaret.NEVER_NEVER but after setting it to NEVER, I could actually never more scroll to somewhere)
3) When user moves scrollbar to the last inserted line, default behavior mentioned in line 1) should be retaken

The only was I see to do this is somehow calculate caret position depending on document length and the current position of scroll, but to be honest I don't really like this way. I would like to know if there is some other, more elegant and correct method doing this?

Thanks, Serhiy.

EDIT: I have found very similar question and answer to it with source code example. Answer can be found here

Upvotes: 2

Views: 1193

Answers (1)

kleopatra
kleopatra

Reputation: 51525

This isn't a complete answer, but the comment area is just too limiting ;-)

My guess is that if you really want to hook into the scrollbar behaviour, then you'd have to play very dirty and intercept the ui-installed MouseListener and wrap the default scrollbar actions (in its ActionMap) with your own and implement the toggle of the caret policy there.

On the other hand: I'm not sure you really want it :-) At least assuming the text is always added at the end, because auto-scrolling only ever happens if the text is inserted before the caret location. All your users have to do

  • for stopping automatic scrolling: move the caret away from the end
  • tor allowing automatic scrolling: move the caret to the end

Upvotes: 2

Related Questions