Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

JScrollPane explicit scroll 1

Status
Not open for further replies.

joelmac

Programmer
Jun 4, 2002
92
CA
Hi there,

I have a JEditorPane inside a JScrollPane. My program adds text to the editorPane and I'd like to have it always scroll to the bottom whenever new text is added. I tried this:
Code:
historyScrollPane.getVerticalScrollBar().setValue(historyScrollPane.getVerticalScrollBar().getMaximum());
but it causes it to scroll to what seems to be random positions. Sometimes it ends up at the bottom, but most of the time not.

Any ideas?

________________________
JoelMac
 
A full working demo from "Core Swing Advanced Programming" by Kim Topley.
The method that does the magic is "scrollRectangleToVisible(...)". Since this is a method from JComponent is will also work for a JEditorPane.

package com.ecc.swing2;

import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.util.Date;

public class AppendingTextPane extends JTextPane {
public AppendingTextPane() {
super();
}

public AppendingTextPane(StyledDocument doc) {
super(doc);
}

// Appends text to the document and ensure that it is visible
public void appendText(String text) {
try {
Document doc = getDocument();

// Move the insertion point to the end
setCaretPosition(doc.getLength());

// Insert the text
replaceSelection(text);

// Convert the new end location
// to view co-ordinates
Rectangle r = modelToView(doc.getLength());

// Finally, scroll so that the new text is visible
if (r != null) {
scrollRectToVisible(r);
}
} catch (BadLocationException e) {
System.out.println("Failed to append text: " + e);
}
}

// Testing method
public static void main(String[] args) {
JFrame f = new JFrame("Text Pane with Scrolling Append");
final AppendingTextPane atp = new AppendingTextPane();
f.getContentPane().add(new JScrollPane(atp));
f.setSize(200, 200);
f.setVisible(true);

// Add some text every second
Timer t = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
String timeString = fmt.format(new Date());
atp.appendText(timeString + "\n");
}

SimpleDateFormat fmt = new SimpleDateFormat("HH:mm:ss");
});
t.start();
}
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top