标签:
使用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