代码如下:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.font.*;
import java.awt.image.*;
public class SpotLight extends Applet implements Runnable{
private String myText;
boolean stop=false;
private Font font;
private int fontSize;
private Thread mythread;
private int spotPosition=50;
private int myTextSize=20;
private int myTextWidth=0;
private int fontHeight,baseLine,w;
public void init(){
String fonts,temp;
myText=this.getParameter("text");
if(myText==null)
myText="你好!";
fonts=this.getParameter("fontSize");
if(fonts==null)
fontSize=20;
else
fontSize=Integer.parseInt(fonts);
font=new Font("TimesRoman",Font.BOLD,fontSize);
FontMetrics fm=getFontMetrics(font);
fontHeight=fm.getHeight();
baseLine=this.getSize().height/2+fontHeight/3;
myTextWidth=fm.stringWidth(myText);
w=fm.stringWidth(myText);
w=(getSize().width-w)/2;
spotPosition=w;
this.setBackground(Color.black);
}
public void start(){
if(stop) stop=false;
if(mythread==null)
{
mythread=new Thread(this);
mythread.start();
}
}
public void stop(){
stop=true;
mythread=null;
}
public void update(Graphics g){
paint(g);
}
public void paint(Graphics g){
g.setFont(font);
g.setColor(Color.blue);
g.drawString(myText,w,baseLine);
g.clipRect(spotPosition,0,myTextSize,getSize().height);
g.setColor(Color.white);
g.drawString(myText,w,baseLine);
spotPosition=(spotPosition+1)%(myTextWidth+100);
}
public void run(){
while(!stop)
{
repaint();
try
{
mythread.sleep(50);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}