How to Get a JTextArea to Hesitate and Scroll Through Data in Java
JTextAreas can display large amounts of text across multiple lines. When embedded in a JScrollPane, JTextAreas will display a scroll bar to allow the user to view data that does not fit in the component's display area. You can program your JScrollPane to hesitate and then automatically scroll with a simple loop and basic thread control. You can customize the amount of time that your program hesitates and how quickly it scrolls.
Instructions
-
-
1
Create a new JScrollPane and add your JTextArea to it with the following code:
JScrollPane scrollPane = new javax.swing.JScrollPane();
scrollPane.setViewportView(textArea);Change "textArea" to the name of your JTextArea. Change the line of code in your program where you add your JTextArea to its parent object to add the JScrollPane object called "scrollPane" instead.
-
2
Create three integer variables to store the hesitation time in seconds before the JTextArea autoscrolls, the delay time in seconds between each scroll and the number of lines the JTextArea should move each time it autoscrolls. Use the following code:
int hesitationTime = 5;
int delayTime = 1;
int scrollIncrement = 10; -
-
3
Create a new Try...Catch statement to catch BadLocationExceptions and InterruptedExceptions with the following code:
try {
} catch (BadLocationException ex) {
System.out.println("Invalid scroll location");
} catch (InterruptedException ex) {
System.out.println("Thread interrupted");
} -
4
Add the following code after the opening bracket in the Try statement to cause the program to wait for a specified time before beginning to scroll the JTextArea:
Thread.sleep(hesitationTime * 1000);
-
5
Enter the following loop immediately below the previous line of code to scroll through the text area at specified intervals:
for (int i = 0; i < textArea.getLineCount(); i += scrollIncrement) {
Thread.sleep(delayTime * 1000);
textArea.setCaretPosition(textArea.getLineEndOffset(i) - 1);
} -
6
Scroll to the very end of the JTextArea. Add this line of code after the For loop:
Thread.sleep(delayTime * 1000);
textArea.setCaretPosition(textArea.getLineEndOffset(textArea.getLineCount() - 1));
-
1