jumptext.java
来自「java的书上例子」· Java 代码 · 共 153 行
JAVA
153 行
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.applet.*;
import javax.swing.*;
/** 一个小应用程序,用来显示一段跳动的文字
* @作者:尉哲明
* @日期:2001年5月 */
/** 定义JApplet类 */
public class JumpText extends JApplet
{
private Thread thread;
private String string;
private Font[] font=new Font[2];
private int speed,locX,locY,directX,directY;
private JumpPanel panel;
/** init()方法,注册鼠标事件监听器以及从网页中获得所需的参数 */
public void init()
{
String param;
addMouseListener(new MouseHandler());//注册鼠标事件监听器
param=getParameter("speed");//从HTML文件中取得参数用来控制文字运动的速度
if(param==null)
speed=50;
else
speed=Integer.valueOf(param).intValue();
font[0]=new Font("TimesRoman",Font.BOLD,30);
font[1]=new Font("TimesRoman",Font.ITALIC,30);
param=getParameter("string");//从HTML文件中取得参数字符串用来显示
if(param==null)
string="Null";
else
string=param;
//下面随机确定文字的初始位置
locX=(int)(Math.random()*(getSize().width-1));
locY=(int)((getSize().height-font[0].getSize()-1)*Math.random());
directX=3;//每次跳动的距离
directY=3;
panel = new JumpPanel();
setContentPane(panel);
}//init()方法结束
/** JApplet类的start()方法 */
public void start()
{//用户返回浏览器时启动动画线程
this.setBackground(Color.white);
if(thread==null)
{
thread=new Thread(panel);
thread.start();
}
}
/** JApplet类的stop()方法 */
public void stop()
{//用户离开浏览器时结束动画线程
thread=null;
}
/** 显示动画的面板类为内部类 */
public class JumpPanel extends JPanel implements Runnable
{
/** 面板组件类的paintComponent()方法 */
public void paintComponent(Graphics g)
{
super.paintComponent(g);
int x,y,space;
StringTokenizer t;
FontMetrics fm;
g.setColor(Color.black);
double d=Math.random();
int i=(int)(d*2);
if(d>0.99) i=1;
g.setFont(font[i]);//随机确定字体
fm=g.getFontMetrics();
space=fm.stringWidth(" ");
x=locX;
y=locY;
for(t=new StringTokenizer(string);t.hasMoreTokens();)
{//文字被分隔成单词后显示
String word=t.nextToken();
int w=fm.stringWidth(word)+space;
if(x>getSize().width)
{
x=x-getSize().width;
}
g.setColor(new Color((int)(Math.random()*256),(int)(Math.random()*256),(int)(Math.random()*256),(int)(Math.random()*256)));
g.drawString(word,x,y);
x+=w;
}
//下面的代码调整显示位置
if(Math.random()>0.99)
{
directX=-directX;
}
locX+=directX;
if(locX>=getSize().width)
{
locX=0;
}
else if(locX<0)
{
locX=getSize().width-1;
}
locY+=directY;
if(locY>=getSize().height)
{
directY=-3;
}
else if(locY<font[0].getSize())
{
directY=3;
}
}//paintComponent()方法结束
/** 在线程中显示动画 */
public void run()
{//动画线程
while(thread!=null)
{
repaint();//调用paintComponent()方法显示文字
try{
thread.sleep(speed);
}catch(InterruptedException e){}
}
}//run()方法结束
}//JumpPanel内部类定义结束
/** 鼠标事件处理内部类,用户可控制动画的启停 */
public class MouseHandler extends MouseAdapter
{
public void mousePressed(MouseEvent e)
{
if(thread==null)
{
start();
}
else
{
thread=null;
}
}//mousePressed()方法定义结束
}//MouseHandler内部类定义结束
}//JumpText类定义结束
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?