Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

setting background color before and after Thread.sleep(n)

807600Nov 27 2007 — edited Nov 27 2007
Would anyone, please, tell me why in my code the color red never shows up?

I set the color to red, then pause the thread for 2 sec (delay) and get back to original color, but I guess delay doesn't apply to setting the background, and this setting back and forth, happens so fast, and I can't see the red background.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.*;

public class ThreadTest{
	private final int mSec = 2000;
	JPanel panel;
	Color color_1 = Color.green;
	Color color_2 = Color.red;
	ThreadTest(){
		JButton button = new JButton("Click");
		button.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent ae){
				holdTheRed(mSec);
				System.out.println("\n background color changed back to color_1 (green)");				
				panel.setBackground(color_1);
			}
		});
		panel= new JPanel();
		System.out.println("\nbackground color is set to color_1 here (green)");
		panel.setBackground(color_1);
		panel.add(button);
	}
	public void holdTheRed(int delay){
		panel.setBackground(color_2);
		System.out.println("\nbackground color changed to color_2  (red)");
		try{
		System.out.println("delay starts");
				Thread.sleep(delay); // 2000 mSec
		System.out.println("delay is over\n");
		}catch(InterruptedException ie){
			System.out.println(ie);
		}
	}

	public void createAndShowGUI(){
		JFrame frame = new JFrame("Test");
		frame.setSize(600, 100);
		frame.getContentPane().add(panel);
		frame.setResizable(false);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);	
	}

	public static void main (String[] args){
		SwingUtilities.invokeLater(new Runnable(){
			public void run(){
				ThreadTest tt = new ThreadTest();
				tt.createAndShowGUI();
			}
		}); 
	}
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 25 2007
Added on Nov 27 2007
6 comments
533 views