日期:2014-05-20 浏览次数:20830 次
import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.Timer; public class AnimationDemo extends JFrame { public AnimationDemo() { add(new MovingMessagePanel("message moving")); } public static void main(String[] args) { AnimationDemo frame = new AnimationDemo(); frame.setTitle("AnimationDemo"); frame.setSize(280, 100); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(EXIT_ON_CLOSE); frame.setVisible(true); } static class MovingMessagePanel extends JPanel { public MovingMessagePanel(String message) { this.message = message; Timer time = new Timer(1000, new TimerListener()); time.start(); } protected void paintComponet(Graphics g) { super.paintComponent(g); if (x > getWidth()) { x = -20; } x += 5; g.drawString(message, x, y); } class TimerListener implements ActionListener { public void actionPerformed(ActionEvent e) { repaint(); } } private int x = 0; private int y = 20; private String message = "Welcome to Java"; } }
@Override public void paint(Graphics g) { // TODO Auto-generated method stub super.paint(g); if (x > getWidth()) { x = -20; } x += 5; g.drawString(message, x, y); }