Slowly Load Text in JTextArea

Have you ever thought of loading text in JTextArea as if a person types. Fine. Let us see this example that demonstrates this.



Start slow!


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class SlowLoadText extends JFrame
{
JTextArea jt;
FileInputStream fin;
int k;
public SlowLoadText()
{
// Set frame properties
setTitle("Slow Load Text");
setLayout(new BorderLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);

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

// Set font to JTextArea jt
jt.setFont(new Font("Times New Roman",Font.BOLD,22));

// Set margin to JTextArea jt, so that it does not appear sticked to the border.
jt.setMargin(new Insets(10,10,10,10));

try
{

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

// Create a new thread
new Thread(new Runnable(){
public void run()
{
try
{
// Read and store every byte in k till end of file
while((k=fin.read())!=-1)
{
try
{

// Append a char, string is needed so "" is attached
jt.append(""+(char)k);

// Set caret position to last for the effect
jt.setCaretPosition(jt.getText().length());

// Sleep for sometime for slow effect
Thread.sleep(200);

// read() and Thread.sleep() throws checked exceptions, so that's why..
}catch(Exception e){}
}
}catch(Exception e){}
}

// Start the thread
}).start();

// fin=new FileInputStream("SlowLoadText.java") throws checked exceptions
}catch(Exception e){}

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

// Add JScrollPane js to JFrame
add(js);

// Make the frame maximized
 setExtendedState(MAXIMIZED_BOTH);
}
public static void main(String args[])
{
new SlowLoadText();
}
}

Watch it!



Posted by at on

Tags: Swing Hacks,