i’m working on applet that displays a moving banner horizontally and when this text banner
reaches the right boundary of the applet window it should be appear reversed from the start of the left boundary, i write the following class to do the work, the problem is that when the text banner reaches the right banner it crashes, the applet goes to infinite loop:
import java.applet.*;
import java.awt.*;
import java.net.*;
import java.io.*;
import javax.swing.*;
/*
<applet code="banner" width=300 height=50>
</applet>
*/
public class TextBanner extends Applet implements Runnable
{
String msg = "Islam Hamdy", temp="";
Thread t = null;
int state;
boolean stopFlag;
int x;
String[] revMsg;
int msgWidth;
boolean isReached;
public void init()
{
setBackground(Color.BLACK);
setForeground(Color.YELLOW);
}
// Start thread
public void start()
{
t = new Thread(this);
stopFlag = false;
t.start();
}
// Entry point for the thread that runs the banner.
public void run()
{
// Display banner
while(true)
{
try
{
repaint();
Thread.sleep(550);
if(stopFlag)
break;
} catch(InterruptedException e) {}
}
}
// Pause the banner.
public void stop()
{
stopFlag = true;
t = null;
}
// Display the banner.
public void paint(Graphics g)
{
String temp2="";
System.out.println("Temp-->"+temp);
int result=x+msgWidth;
FontMetrics fm = g.getFontMetrics();
msgWidth=fm.stringWidth(msg);
g.setFont(new Font("ALGERIAN", Font.PLAIN, 30));
g.drawString(msg, x, 40);
x+=10;
if(x>bounds().width){
x=0;
}
if(result+130>bounds().width){
x=0;
while((x<=bounds().width)){
for(int i=msg.length()-1;i>0;i--){
temp2=Character.toString(msg.charAt(i));
temp=temp2+temp;
// it crashes here
System.out.println("Before draw");
g.drawString(temp, x, 40);
System.out.println("After draw");
repaint();
}
x++;
} // end while
} //end if
}
}
Let’s start with…
JAppletinstead ofApplet)paintmethods of top level containers. There are lots of reasons, the major one that is going to effect you is top level containers are not double buffered.Threadis simply over kill.paintmethod. You’ve tried to perform ALL you animation within thepaintmethod, this is not howpaintworks. Think ofpaintas a frame in film, it is up to (in your case) the thread to determine what frame where up to, and in fact, it should be preparing what should painted.repaintis a “request” to the paint sub system to perform an update. The repaint manager will decide when the actual repaint will occur. This makes performing updates a little tricky…Updated with Example
Updated with additional example
Now, if you want to be a little extra clever…you could take advantage of a negative scaling process, which will reverse the graphics for you…
Updated timer…
And the updated paint method…
Updated with “bouncing”…
This replaces the
TextPanefrom the previous exampleAs the text moves beyond the right boundary, it will “reverse” direction and move back to the left, until it passes beyond that boundary, where it will “reverse” again…