📄 animationtext2.java
字号:
//AnimationText2.java
//实验1 文字滚动条
/*实验目的:
1.了解动画的原理
2.进一步了解多线程的概念
3.运用Java的多线程实现动画的应用*/
/*实验任务:
设计一个文字显示面板,文字可以在面板上实现滚动显示。
本实验有两个练习,一个是通过Thread来实现动画时间间隔的设置。
另一个是通过Timer来实现对动画时间间隔的制定*/
//练习1 用JApplet实现动画
//练习2 用Application实现动画
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class AnimationText2 extends JPanel implements ActionListener{
Timer timer; //timer驱动动画
int x,y; //文字的坐标
String string="进入动画世界"; //要显示的文字
public AnimationText2(){
x=0;
y=100;
this.setBackground(Color.black);
this.setForeground(Color.red);
}
public void paintComponent(Graphics g){
/*javax.swing.JComponent类是Component的子类,也是许多swing包的父类。
意味着,swing包中的许多组件也有paint()、update()和repaint()这三种方法。*/
/*JComponent组件本身有一个方法paintComponent(Graphics g)可用来绘制JComponent组件的内容。同样,程序员不能直接
调用该方法,也不得不通过调用repaint(Graphics g)来实现间接调用该方法,从而达到对JComponent内容的输出。*/
repaint(); //代码1,清除上次的绘制内容
g.setFont(new Font("姚体",Font.BOLD,30));
g.drawString(string,x,y);
x+=10;
if(x>400) x=0;
}
public void startAnimation(){
if(timer==null){
timer=new Timer(100,this); //代码2,创建一个定时器timer
timer.start();//代码3,timer开始驱动动画
}
if(!timer.isRunning()){//如果timer没有运行
timer.start();//代码4,让timer重新开始驱动动画
}
}
public void stopAnimation(){
timer.stop();
}
public Dimension getMinmumSize(){
return getPerferredSize();
}
public Dimension getPerferredSize(){
return new Dimension(200,200);
}
public void actionPerformed(ActionEvent e){
repaint(); //重新绘制文字
}
public static void main(String[] args){
AnimationText2 text2=new AnimationText2();
JFrame frame=new JFrame("文字动画演示");
Container container=frame.getContentPane();
container.add(text2);
frame.setSize(400,240);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
text2.startAnimation();
}
}
//思考:比较用Thread和Timer实现动画的异同
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -