下面是我的程序的一部分
在eclipse中运行时,定时的方法不是每秒运行一次,而是越来越快,求解
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.Timer;
import javax.swing.JPanel;
public class as extends JFrame {
public static void main(String[] args) {
// TODO Auto-generated method stub
as frame = new as();
jump jump = new jump();
frame.add(jump);
frame.setTitle("跳刺");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 250);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
jump. setBackground(Color.white);
}
}
class jump extends JPanel {
int a = 794 ;
public void refresh(){
int delay =1000;
ActionListener listener = new ActionListener(){
public void actionPerformed(ActionEvent arg0){
repaint();
}
};
Timer timer = new Timer(delay,listener);
timer.start();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.print(a+" ");
refresh();
}
}
可能每次都new了一个timer出来。。。可以设置成单例的
错误就是每次调用后都new了一个新的定时器。
下面是修改后的代码,你复制后就可以运行。
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class as extends JFrame {
public static void main(String[] args) {
// TODO Auto-generated method stub
as frame = new as();
jump jump = new jump();
frame.add(jump);
frame.setTitle("跳刺");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 250);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
jump. setBackground(Color.white);
}
}
class jump extends JPanel {
int delay =1000;
int a = 794 ;
public jump(){
java.util.Timer timer;
timer = new Timer(true);
timer.schedule(
new java.util.TimerTask() { public void run()
{
repaint();
}
},0, 1000);
};
//Timer timer = new Timer(delay,listener);
//timer.start();
protected void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.print(a+" ");
}
}
每次绘制都会调用 paintComponent,然后调用 refresh,就生成一个 Timer,导致不停的生成 Timer。
把生成 Timer 的代码放到构造函数里就可以了。