Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

Repaint the screen in a for loop

  Asked By: Conrad    Date: Jul 06    Category: Java    Views: 1567
  

I am working in 2D graphics........
I have a small object that is to be moved from one
point on the screen to the other in small steps
smoothly.........
For this I called repaint in a 'for loop' inside which
the new coordinates are being calculated....
But it first calculates all the coordinates from start
to the end point and on repainting I see my object to
be directly at the end point....... and not a smooth
motion from start to end as desired.........
Please help........

Share: 

 

2 Answers Found

 
Answer #1    Answered By: Jonathan Harrison     Answered On: Jul 06

try to execute this program....



import java.awt.*;
import java.awt.event.*;

class Face extends Frame implements Runnable
{
int x=0,direction=0;
Face()
{
setSize(300,300);
setVisible(true);
}
public void paint(Graphics g)
{
g.setColor(Color.blue);
g.fillOval(70+x,90+x,140+x,100+x);
g.setColor(Color.red);
g.fillOval(100+x,120+x,20+x,20+x);
g.setColor(Color.red);
g.fillOval(165+x,120+x,20+x,20+x);
}

public void run()
{
while(true)
{
if(direction==0)
{
x++;
if(x==100)
{
direction=1;
}
}
else if(direction==1)
{
x--;
if(x==0)
{
direction=0;
}
}

repaint();

try
{
Thread.sleep(100);
}
catch(Exception e)
{
}
}
}


public static void main(String args[])
{

Face obj = new Face();
Thread t = new Thread(obj);
t.start();
}
}

 
Answer #2    Answered By: Gerald Cruz     Answered On: Jul 06

put " Thread.currentThread.sleep(500); " to the center of your for loop
and enjoy it.

 
Didn't find what you were looking for? Find more on Repaint the screen in a for loop Or get search suggestion and latest updates.




Tagged: