Question

I'm working with JFrame, and I have a while loop. Inside that while loop I change the background of the frame to black then white, and have it do it again. However, I need it to pause for a second or two in between changing so you can actually see it. Thread.sleep(), and Timer don't seem to work. Can anyone help?

No correct solution

OTHER TIPS

If you want to use a timer from swing this is the proper way to do it:

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

}

And if you want to use Thread.sleep(), you can do something like this:

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

}

If you have any questions about the code please feel free to ask.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top