Load Text in JTextArea with Random Speed

Load Text in JTextArea Randomly

Previously, we've seen how to load text slowly, now let us see randomly, the only one that variate this post and the previous post of Slowly Loading Text in JTextArea is the thread's sleep time, in that post, 200 a fixed int was given, but now it's random.

Let's go random!

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import java.util.*;
class RandomLoadText extends JFrame
// Declare JTextArea reference variable
JTextArea jt;
// Create an int variable named k. Default value of k=0, because java doesn't support garbage values.
int k;
public RandomLoadText()
// Set frame properties
setTitle("Random Loading Speed");
setLayout(new BorderLayout());

// Create JTextArea jt
jt=new JTextArea();

// Create JScrollPane for jt
JScrollPane js=new JScrollPane(jt);

// Set margin, so that text will not stick to borders
jt.setMargin(new Insets(10,10,10,10));

// Set a bigger font, for better appearance
jt.setFont(new Font("Times New Roman",Font.BOLD,22));

// Add JScrollPane to frame

// Create a new thread
new Thread(new Runnable(){

// What to be done?
public void run()

// The main code!

// Create FileInputStream fin pointing this file
FileInputStream fin=new FileInputStream("RandomLoadText.java");

// Read each char & store it in k. Do this till end of file.

// Append each char to JTextArea, "" is attached as append() takes String not char!

// Set caret position to last, this makes sense.

// Give the random effect, sleep the thread randomly each time with a value that is <200
Thread.sleep(new Random().nextInt(200));

}catch(Exception e){}

// Start the thread (start writing)

// Make the frame wide spread over the screen.

public static void main(String args[])
new RandomLoadText();

 That's it, as usual everything explained above, take time to see other posts in Swing Hacks category.

Posted by at on

Tags: Swing Hacks,