您的位置:首页 > 编程语言 > Java开发

用java来实现滚动消息

2010-08-08 14:38 232 查看
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;

class Test extends Canvas implements Runnable{

// TODO Auto-generated method stub

String msg;
int msgLength;
int x_character=0;
Font wordFont;
int width,height;

Image offImg;
Graphics offG;
Thread runThread;
static boolean stop;
int delay;

public Test(int width,int height){
this.width=width;
this.height=height;
first();
}
public void first(){
wordFont=new Font("TimesRoman",Font.PLAIN+Font.BOLD,15);
msg="小清要加油";
msgLength=msg.length();

delay=600;
stop=false;
runThread=new Thread(this);
runThread.start();
}

public void run(){
while(!stop){
if(x_character++>=msgLength){
x_character=0;
offG=null;
}
repaint();
try{
Thread.sleep(delay);
}catch(InterruptedException e){

}
}
}
public void paint(Graphics g){
g.setFont(wordFont);
g.setColor(Color.red);
g.drawString(msg.substring(0,x_character),10, height/2);
}
public void update(Graphics g){

if(offG!=null){
paint(offG);
g.drawImage(offImg,0,0,this);
}else{
paint(g);
offImg=createImage(width,height);
offG=offImg.getGraphics();
}
}
public static void stop(){
stop=true;
}
public static void main(String[] args){

int width=200;
int height=100;
Test test=new Test(width,height);
JFrame frame=new JFrame("滚动的消息");

frame.setLocation(0,0);
frame.setSize(width,height);

frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){

Test.stop();
System.exit(0);
}
});
frame.getContentPane().add(test);
frame.setVisible(true);

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: