Jump to content



Photo

Making JScrollBars behave

java jscrollpane jscrollbar scrolling swing

  • Please log in to reply
1 reply to this topic

#1 Seizure1990

Seizure1990

    Neowinian Senior

  • Joined: 17-February 08
  • Location: NYC

Posted 08 October 2012 - 02:43

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());
		}
	}

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 ever-so-slightly 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:
Posted Image

What it should look like:
Posted Image

Thanks for any help guys!


#2 OP Seizure1990

Seizure1990

    Neowinian Senior

  • Joined: 17-February 08
  • Location: NYC

Posted 09 October 2012 - 22:10

Nobody here can help me wrangle the savage beast that is javax.swing? How sad! :'[



Click here to login or here to register to remove this ad, it's free!