码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-08-16 14:46:06      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:

使用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();
			}
		}
	}
}


实现消息在窗口中移动


技术分享技术分享


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

标签:

原文地址:http://blog.csdn.net/qq_24653023/article/details/52220361

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!