暂停程序

时间:2013-10-29 16:18:08

标签: java pausing-execution

我正在使用JFrame,我有一个while循环。在while循环中,我将框架的背景更改为黑色然后是白色,并让它再次执行。但是,我需要在更改之间暂停一两秒,以便您可以实际看到它。 Thread.sleep()Timer似乎无效。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

如果您想使用timer中的swing,这是正确的方法:

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;

public class Animation extends JFrame implements ActionListener {

private Timer t;
private Color myColor;
private int howManyTimesIwantThis;
private int count = 0;

public Animation() {
    t = new Timer(1000, this); // actionPerformed will be called every 1 sec
    t.start();
    this.howManyTimesIwantThis = 10;
    this.setVisible(true);
    this.setSize(500, 500);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLocationRelativeTo(null);

    myColor = Color.blue;
}

public void actionPerformed(ActionEvent e) {
    if (count < howManyTimesIwantThis) {
        count++;
        if (myColor.equals(Color.blue)) {
            myColor = Color.red;
        } else {
            myColor = Color.blue;
        }
        repaint(); //calls the paint method
    }
}

public void paint(Graphics g) {
    super.paint(g);

    g.setColor(myColor);
    g.fillRect(0, 0, this.getWidth(), this.getHeight());

    g.dispose();
}

}

如果你想使用Thread.sleep(),你可以这样做:

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JFrame;

public class Animation extends JFrame{

private Color myColor;
private int howManyTimesIwantThis;
private int count = 0;

public Animation() {
    this.howManyTimesIwantThis = 10;
    this.setVisible(true);
    this.setSize(500, 500);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLocationRelativeTo(null);

    myColor = Color.blue;
}

public void paint(Graphics g) {
    super.paint(g);

    while (count < howManyTimesIwantThis) {
        count++;
        if (myColor.equals(Color.blue)) {
            myColor = Color.red;
        } else {
            myColor = Color.blue;
        }
        g.setColor(myColor);
        g.fillRect(0, 0, this.getWidth(), this.getHeight());
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    g.dispose();
}

}

如果您对该代码有任何疑问,请随时提出。

相关问题