sreeku24 sreeku24 - 8 days ago 8
Java Question

Print String character one by one using threads

I am trying to print characters one by one on the animated banner, but i can't get the desired result.

I am getting the result with my code but not the one I am looking for. I am getting the banner and result of characters also.

But those characters are overlapping one another.

Please check below code

import java.awt.*;
import java.io.*;

//Banner class
class Banner extends Frame implements Runnable
{
boolean stop=false;
String str="Sreedhar Practice seassion";
//constructor
public Banner()
{
setLayout(null);
setBackground(Color.cyan);
setForeground(Color.blue);
}//end of constructor

//image paint settings methosd
public void paint(Graphics g)
{
Font f=new Font("Courier",Font.BOLD,40);
g.setFont(f);
for (int i=0;i<=str.length() ;i++ )
{
char ch=str.charAt(i);
String c=String.valueOf(ch);
g.drawString("\t"+c,10,100);
try
{
Thread.sleep(100);
}
catch (InterruptedException ie)
{
}
//char ch=str.carAt(0);
//str=str.substring(1,str.length());
//str=str+ch;
if (stop)
{
return;
}
}

}//image paint settings methosd end

//start of run method
public void run()
{
if (stop)
{
return;
}
}
}//end of run method

//main method starting
public static void main(String[] args)throws IOException
{
Banner b=new Banner();
b.setSize(400,400);
b.setTitle("Sreedhar Banner");
b.setVisible(true);
Thread t=new Thread(b);
t.start();
System.in.read();
b.stop=true;
}//end of main method
}//end of class Banner


This is my code, but am not getting the desired result what i want.

Answer

few bugs over here first:

}//end of run method

one curly brace is redundant

second:

for (int i=0;i<=str.length() ;i++ )

should be:

for (int i=0; i < str.length(); i++)

third:

g.drawString("\t" + c, 10 + PRINT_FACTOR * i, 100);

where PRINT_FACTOR should be counted or choosed by expirement