When using the Timer Class guide package, be careful not to guide the wrong package, there are several different timer classes
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 messagethis.setlayout (new GridLayout (2, 1)); Add (New Movingmessagepanel (" Message moving), add (New Movingmessagepanel ("2410!", 500)); public static void Main (string[] args) {Animationdemo frame = new Animationdemo (); Frame.settitle ("Animationdemo"); Frame.setlocationrelativeto (NULL); Center the Frameframe.setdefaultcloseoperation (jframe.exit_on_close); frame.setsize (280); Frame.setvisible ( true);} Static Class Movingmessagepanel extends JPanel {private String message = "Welcome to Java";p rivate int xcoordinate = 0;pri vate int ycoordinate = 20;public Movingmessagepanel (String message, int delay) {this.message = message;//Create a timertimer 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) {Repai NT ();}}}}
Implementing messages moving through windows
"Fundamentals of Java language Programming"--animation of event-driven programming--timer class