Search code examples
javaswingtimergraphics2d

Timer move an object of Graphics2D over an image in JFrame? (Sunrise program example)


I'm trying to write a program to design a sunrise animation by using Timer and JFrame and JComponent. The Object of Graphics2D is the sun which is going to move over JFrame. My problem is that I'm not sure where to place the Timer and move the Graphicc2D! Here is what I have done so far to place an image in JFrame and then place the sun on that image. Please tell me where I can manage to move the sun. where should I define Timer class? In JFrame or JComponent or main class?

public class Main(){

     public static void main(String[] args){

          myFrame frame = new myFrame();
     }
}

class myFrame extends JFrame
{
    public  myFrame()
    {
        Draw component = new Draw();
        add(component);
    }
}

class Draw extends JComponent
{
    public Draw()
    {
          //Read the image here
          //set the newImage
    }

    public void paintComponent(Graphics g)
    {
            Graphics2D g2 = (Graphics2D) g; 
            g2.drawImage(newImage, 0, 0, null);
            g2.fill(new Ellipse2D.Double(x,y,20,20));
            //For the sunrise I need to change x,y during the Timer class!!
    }

}

Solution

  • This should do:

    int x, y;
    Timer timer = new Timer(50, new ActionListener(){
    
        public void actionPerformed(ActionEvent evt){
            // update x and y 
    
            repaint();
        }
    });
    

    Don't forget to start the timer, (it's preferred to do so, in the constructor).