'Changing the color of frame background repeatedly

So i want my methods to change the background color of my Frame every like 0.2 seconds and i tried a lot of diferent things like new methods and Threat sleep/wait but nothing worked even though trying it with System.out.print did. I have no idea what could work now so would be ice if someone helped me out, thank you beforehand!

PS.: dont mind the variable and method names was having fun with my friends xD

public void poggersModeOn()
{
    f.setTitle("Insane rainbow pogg mode!!!!1!!!11!!1!! ");
    int rot = (int)(Math.random()*255+1);
    int gruen = (int)(Math.random()*255+1);
    int blau = (int)(Math.random()*255+1);
    f.setBackground(new Color(rot, gruen, blau));
}

public void poggersModeOff()
{
    f.setTitle("Navigationssystem");
    f.setBackground(new Color(255, 255, 255));
}

public void pogmethode() {
    while(pogmode==true)
    {
        poggersModeOn();
        //wait function right here
    }
}


Solution 1:[1]

Assuming your using Swing, then you should use a Swing Timer, see How to Use Swing Timers

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Main {
    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            Timer timer = new Timer(250, new ActionListener() {
                private Random rnd = new Random();
                @Override
                public void actionPerformed(ActionEvent e) {
                    int red = rnd.nextInt(255);
                    int green = rnd.nextInt(255);
                    int blue = rnd.nextInt(255);
                    setBackground(new Color(red, green, blue));
                }
            });
            timer.start();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(400, 400);
        }
    }
}

Why? Because Swing is single threaded (and not thread safe). See Concurrency in Swing for more details

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MadProgrammer