Load Text in JTextArea Randomly
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());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
// 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
add(js);
// Create a new thread
new Thread(new Runnable(){
// What to be done?
public void run()
{
// The main code!
try
{
// 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.
while((k=fin.read())!=-1)
{
// Append each char to JTextArea, "" is attached as append() takes String not char!
jt.append((char)k+"");
// Set caret position to last, this makes sense.
jt.setCaretPosition(jt.getText().length());
// 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)
}).start();
// Make the frame wide spread over the screen.
setExtendedState(MAXIMIZED_BOTH);
}
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.
No comments:
Post a Comment