
May 19th, 2004, 05:28 AM
|
 |
Sarcastic Member
Power Poster
|
|
Join Date: Oct 2003
Location: .NET2.0 / VS2005 Developer
Posts: 7,076
|
|
cached a copy here, as that was a very useful article.. nice find abramia
Quote:
From: Simon Righarts (the_spud@hotmail.com)
Subject: Re: Scroll to bottom of JTextArea in JScrollPane
Newsgroups: comp.lang.java.gui
Date: 2003-09-28 03:48:46 PST
"David Rowe" <djrow2@dodo.com.au> wrote in message
news:53ac0837.0309271703.2aec1b81@posting.google.com...
> I have a JTextArea that I'm using as a status window. How do I make
> the associated JScrollPane always stay scrolled to the bottom of this
> text area to show the latest message added ?
This must be the most frequently-asked question in here.
Anyway, you have three options (or more)
1: get the document underlying the text area, set the caret position to
document.length
2: get the vertical scroll bar from the scrollpane, and set that to it's
maximum value
3: call scrollRectToVisible - which, I think (never played with it myself)
scrolls smoothly.
Whichever one you decide to run with, I'd extend JTextArea (whichever
constructer you use, just override that and pass all it's arguments to the
super-constructer) and override whichever JTextArea append methods you're
using (call super.append(the arguments), then whichever method you use to
scroll to end).
this little snippet of code will show you all three variations:
disadvantage of method one: it sets the caret position, thus losing whatever
selections were made in the text area.
disadvantage of method three: It cranks up a new thread, which may not be
the ideal solution if you're appending fairly frequently.
Code:
JTextArea test = new JTextArea();
JScrollPane testScroller = new JScrollPane(test);
private void somemethod(){
test.addGreatBigLumpOfText(); //so we need to scroll - dummy method ;)
//method one
test.setCaretPosition(test.getDocument().getLength()-1);
//method two
testScroller.getVerticalScrollBar().setValue(
testScroller.getVerticalScrollBar().getMaximum()
);
//method three
scrollToEnd();
}
private void scrollToEnd(){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
if (isAdjusting()){
return;
}
int height = test.getHeight();
test.scrollRectToVisible(new Rectangle(0, height - 1,1, height));
}
});
}
private boolean isAdjusting(){
JScrollBar scrollBar = testScroller.getVerticalScrollBar();
if (scrollBar != null && scrollBar.getValueIsAdjusting()){
return true;
}
return false;
}
NB: I didn't write the code for scrollToEnd/isAdjusting (sourced from post
3f69e117$0$59152$e4fe514c@dreader9.news.xs4all.nl by Mr. Cube)
|
Last edited by cjard; May 19th, 2004 at 05:46 AM.
|