当前位置: 技术问答>java相关
请问JAVA的定时器如何设置
来源: 互联网 发布时间:2015-02-14
本文导语: 就是让JAVA每个一段时间自动中断一次,执行一个函数的方法? | public final static int ONE_SECOND = 1000; ... timer = new Timer(ONE_SECOND, new ActionListener() { public void actionPerformed(ActionEvent evt)...
就是让JAVA每个一段时间自动中断一次,执行一个函数的方法?
|
public final static int ONE_SECOND = 1000;
...
timer = new Timer(ONE_SECOND, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//...Perform a task...
}
});
//start the timer:
timer.start();
When the task is finished, the timer's action listener stops the timer:
if (/* task is done */) {
...
timer.stop();
...
}
...
timer = new Timer(ONE_SECOND, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//...Perform a task...
}
});
//start the timer:
timer.start();
When the task is finished, the timer's action listener stops the timer:
if (/* task is done */) {
...
timer.stop();
...
}
|
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class ballFrame extends JFrame implements ActionListener
{
private Timer timers;
private int dx,dy,x,y;
private int add;
private int startx,starty;
private JButton jb;
private Color c;
private int xchose,ychose;
private int upline;
private boolean flag;
public ballFrame()
{
Container ctp=getContentPane();
ctp.setLayout(null);
dx=10;
dy=20;
startx=60;
starty=50;
x=5;
y=7;
flag=true;
setBackground(Color.black);
c=getBackground();
jb=new JButton ("Start");
ctp.add(jb);
jb.setBounds(20,350,70,20);
jb.addActionListener(this);
timers=new Timer(80,this);
//g.dispose();
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
setSize(700,400);
setResizable(false);
setTitle("ball");
setVisible(true);
}
public void paint(Graphics g)
{ //super.paint(g);
g.setColor(Color.red);
g.fillOval(dx,dy,10,10);
//this.setBackground(Color.black);
g.setColor(Color.green);
for (int i=0 ;i
import javax.swing.*;
import java.awt.event.*;
class ballFrame extends JFrame implements ActionListener
{
private Timer timers;
private int dx,dy,x,y;
private int add;
private int startx,starty;
private JButton jb;
private Color c;
private int xchose,ychose;
private int upline;
private boolean flag;
public ballFrame()
{
Container ctp=getContentPane();
ctp.setLayout(null);
dx=10;
dy=20;
startx=60;
starty=50;
x=5;
y=7;
flag=true;
setBackground(Color.black);
c=getBackground();
jb=new JButton ("Start");
ctp.add(jb);
jb.setBounds(20,350,70,20);
jb.addActionListener(this);
timers=new Timer(80,this);
//g.dispose();
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
setSize(700,400);
setResizable(false);
setTitle("ball");
setVisible(true);
}
public void paint(Graphics g)
{ //super.paint(g);
g.setColor(Color.red);
g.fillOval(dx,dy,10,10);
//this.setBackground(Color.black);
g.setColor(Color.green);
for (int i=0 ;i