1

I'm trying to make a Java program that displays a red-green-blue background, with a 1-second pause after updating. I tried this:

Container content = frame.getContentPane();

            content.setBackground(Color.RED);
            Thread.sleep(1000); 
            content.setBackground(Color.GREEN);
            Thread.sleep(1000);
            content.setBackground(Color.BLUE);

However, this just waits 2 seconds then displays a blue background. Can anyone give me a fix?
I'm a total noob at Swing so a little explanation would be greatly appreciated. Also, is there any way to loop the colour change? Thanks!

heftymouse
  • 11
  • 3
  • 2
    Don't block the EDT (Event Dispatch Thread). The GUI will 'freeze' when that happens. See [Concurrency in Swing](https://docs.oracle.com/javase/tutorial/uiswing/concurrency/) for details and the fix. – Andrew Thompson Jun 28 '19 at 06:57
  • 2
    "I'm a total noob at Java" - note that in many cases the combination of "I'm new to Java" and "I want to do some UI stuff" is a reason for a lot of headaches. So if you're really as much a noob as you claim to be then I'd advise you to first get past that stage and get a firm grasp of the basic concepts before diving head first into the murky waters of UI development. – Thomas Jun 28 '19 at 07:03
  • You need to use a Swing Timer, [For example](https://stackoverflow.com/questions/34746795/creating-an-animated-4x4-grid-in-java/34748083#34748083) – Frakcool Jun 28 '19 at 15:29

0 Answers0