使用计时器暂停程序执行



我想暂停 Swing 程序的执行指定的时间。当然,我使用的第一件事是 Thread.sleep(100)(因为我是一个菜鸟)。然后我知道我的程序不是线程安全的,所以我决定使用 Timer 和其他程序员的一些建议。问题是我无法从中获取任何资源,从中学习如何使用计时器延迟线程。他们中的大多数使用计时器来延迟执行。请帮我解决这个问题。我在下面提供了一个可编译的代码片段。

import javax.swing.*;
import java.awt.*;
public class MatrixBoard_swing extends JFrame{
    public static void main(String[] args){
        SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            MatrixBoard_swing b = new MatrixBoard_swing();      
          }
       });
    }
    MatrixBoard_swing(){
        this.setSize(640, 480);
        this.setVisible(true);
        while(rad < 200){
            repaint();
            rad++;
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    int rad = 10;
    public void paint(Graphics g){
        super.paint(g);
        g.drawOval(400-rad, 400-rad, rad, rad); 
    }
}

编辑:我对计时器实现的试用版(请告诉我是否错误):

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MatrixBoard_swing extends JFrame implements ActionListener{
    Timer timer;
    public static void main(String[] args){
        SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            MatrixBoard_swing b = new MatrixBoard_swing();      
          }
       });
    }
    MatrixBoard_swing(){
        this.setSize(640, 480);
        this.setVisible(true);
        timer = new Timer(100, this);
        timer.start();
    }
    int rad = 10;
    public void paint(Graphics g){
        super.paint(g);
        g.drawOval(400-rad, 400-rad, rad, rad); 
    }
    @Override
    public void actionPerformed(ActionEvent arg0) {
        repaint();
        rad++;
        if(rad >= 200){
            timer.stop();
        }
    }

所以而不是...

while(rad < 200){
    repaint();
    rad++;
    try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

你只需要稍微扭转一下逻辑...

Timer timer = new Timer(1000, new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        rad++;
        if (rad < 200) {
            repaint();
        } else {
            ((Timer)evt.getSource()).stop();
        }
    }
});
timer.start();

基本上,Timer将充当 Thread.sleep() ,但以一种很好的方式,不会破坏 UI,但允许您在执行之间注入延迟。 每次执行时,您都需要增加值,测试"停止"条件,否则更新...

看看如何使用摆动计时器和其他 3, 800 个关于 SO 主题的问题......

最新更新