循环中的随机背景色(Java)

循环中的随机背景色(Java),java,Java,我想在每次调用“重新绘制”时更改面板的背景色。我有一个困难的时候做它与挫折,所以我想知道,如果一个drawRect与相同的尺寸作为框架将做同样的工作,或者这是一个不可以吗 public class Artwork extends JPanel implements Runnable { boolean running = false; Random rng = new Random(); public Artwork() { this.setOpaque(true); } publ

我想在每次调用“重新绘制”时更改面板的背景色。我有一个困难的时候做它与挫折,所以我想知道,如果一个drawRect与相同的尺寸作为框架将做同样的工作,或者这是一个不可以吗

public class Artwork extends JPanel implements Runnable {

boolean running = false;
Random rng = new Random();

public Artwork() {
    this.setOpaque(true);
}

public void Start() {
    running = true;
    Thread thread = new Thread(this);
    thread.start();
}

public void Stop() {
    running = false;
}

public void run() {
    while (running = true) {
        repaint();
        try {
            Thread.sleep(2500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    super.setBackground(randomColor());
}

public Color randomColor() {
    int r = rng.nextInt(255);
    int g = rng.nextInt(255);
    int b = rng.nextInt(255);
    return new Color(r, g, b);
}
使用此选项,无论Thread.sleep如何,背景颜色都会快速变化

使用此选项,无论Thread.sleep如何,背景颜色都会快速变化

绘画方法仅适用于绘画

不要在paintComponent方法中调用setBackground之类的方法来更改组件的属性。属性更改时,Swing组件会自动重新绘制自身。当组件一次又一次地重新绘制自身时,这将导致无限循环


解决方案是在调用repait方法之前在线程中调用setBackground方法。

需要代码。挫折总是对我有用。在run方法中设置背景非常有效。谢谢