• 0

Making JScrollBars behave


Question

I have a JScrollPane and JTextPane that is to be used in a chat program. Therefore, I'd like standard chat window behavior where the scroll bar continues to automatically scroll down if (and ONLY if) the scroll bar was already at the bottom, and otherwise leaves it at the current value.

The only solution I've found through searching which comes close to working involves setting the caret position for the JTextPane, but that still has issues. First, the relevant code:


public synchronized void updateChat(){
JScrollBar scrollBar = chatView.getVerticalScrollBar();
boolean scrollBarVisible = scrollBar.isVisible();
boolean scrollBottom = false;

if(scrollBarVisible)
scrollBottom = scrollBar.getMaximum() == scrollBar.getValue() + scrollBar.getVisibleAmount();

recentChat.setText(Utils.buildRecentHistory(chatManager.getMessages()));

if(!scrollBarVisible && scrollBar.isVisible() || scrollBottom) {
recentChat.setCaretPosition(recentChat.getDocument().getLength());
}
}
[/CODE]

chatView is a JScrollPane. The problem with this method is that even though the caret is set to the maximum value, the scroll bar will actually just be [i]ever-so-slightly[/i] away from all the way down. Then, when another message comes in, it doesn't think it should continue to scroll down since it's only close to bottom, but not actually.

What it looks like after the caret reset:

2F0Ji.png

What it should look like:

8hTCV.png

Thanks for any help guys!

Link to comment
Share on other sites

1 answer to this question

Recommended Posts

This topic is now closed to further replies.