0

我正在使用JFrame,并且我有一个 while 循环。在那个while循环中,我将框架的背景更改为黑色然后是白色,然后让它再做一次。但是,我需要它在更改之间暂停一两秒钟,这样你才能真正看到它。Thread.sleep(),并且Timer似乎不起作用。任何人都可以帮忙吗?

4

1 回答 1

0

如果您想使用 a timerfromswing这是正确的方法:

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();
}

}

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

于 2013-10-29T16:59:37.420 回答