【JAVA语言程序设计基础篇】--事件驱动程序设计--Timer类的动画

使用Timer类导包的时候,注意不要导错包,有好几个不同的Timer类

package chapter16;

import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

@SuppressWarnings("serial")
public class AnimationDemo extends JFrame {
	public AnimationDemo() {
		// Create a MovingMessagePanel for displaying a moving message
		this.setLayout(new GridLayout(2, 1));
		add(new MovingMessagePanel("message moving?", 1000));
		add(new MovingMessagePanel("2410!", 500));
	}
	public static void main(String[] args) {
		AnimationDemo frame = new AnimationDemo();
		frame.setTitle("AnimationDemo");
		frame.setLocationRelativeTo(null); // Center the frame
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(280, 100);
		frame.setVisible(true);
	}
	static class MovingMessagePanel extends JPanel {
		private String message = "Welcome to Java";
		private int xCoordinate = 0;
		private int yCoordinate = 20;

		public MovingMessagePanel(String message, int delay) {
			this.message = message;

			// Create a timer
			Timer timer = new Timer(delay, new TimerListener());
			timer.start();
		}

		public void paintComponent(Graphics g) {
			super.paintComponent(g);

			if (xCoordinate > getWidth()) {
				xCoordinate = -20;
			}
			xCoordinate += 5;
			g.drawString(message, xCoordinate, yCoordinate);
		}

		class TimerListener implements ActionListener {
			/** Handle ActionEvent */
			public void actionPerformed(ActionEvent e) {
				repaint();
			}
		}
	}
}


实现消息在窗口中移动





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值