I have been trying for hours to figure out my mistake in a simple program in java. I wish to display the change in backgroundcolor after 200 ms so I wrote this program but it's not showing correct output.
It's a long program ahead thanks in advance for reading.
public class bgColor extends Applet implements Runnable
{
Thread timer=null;
int c,flag;
public void init()
{
c=0;
setBackground(new Color(255,255,255));
}
public void start()
{
if(timer==null)
{
timer=new Thread(this);
timer.start();
}
}
public void paint(Graphics g)
{
switch(c)
{
case 0:setBackground(Color.white);
break;
case 1:setBackground(Color.blue);
break;
case 2:setBackground(Color.green);
break;
case 3:setBackground(Color.red);
break;
}
if(c==4)
{
flag=0;
}
else if(c==0)
{
flag=1;
}
if(flag==0)
{
c--;
}
else if(flag==1)
{
c++;
}
}
public void stop()
{
timer=null;
}
public void run()
{
if(timer!=null)
{
repaint();
c++;
try
{
Thread.sleep(200);
}
catch(InterruptedException e){}
}
timer=null;
}
}
I basically set up a switch for changing background Color after certain intervals but it's showing only red Color throughout.
It would also be of enormous help if someone could suggest where I can read up how the program runs step by step like I think probably init(), then start() then run() then paint() then stop() but it's purely my guess. I need an authentic source.
Have you tried printing c
?
The thread runs more often than paint
since even if you call repaint
a million times, it only paints at most once per frame. The sleep helps, but it only reduces the risk of a race condition instead of eliminating the issue.
You also have a race condition where c
can go above 4 and flag will never toggle. Try using c >= 4
and c <= 0
instead to avoid this. Based on your description, this is probably your issue.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.