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);
}
}
这是一个使用Java实现的滚动文字程序,通过Canvas、Thread和Graphics类实现。程序创建了一个字符串msg,设置滚动速度并启动线程,不断更新字符位置并重绘,当字符超出屏幕宽度时重新开始。此外,还包含窗口关闭事件监听,用于停止滚动并退出程序。
1万+

被折叠的 条评论
为什么被折叠?



