Suhail Gupta
Suhail Gupta

Reputation: 23276

using repaint() method in this code

I am having a problem using the repaint method in the following code.Please suggest how to use repaint method so that my screen is updated for a small animation. This is my code :

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class movingObjects extends JPanel {
   Timer timer;
   int x = 2, y = 2, width = 10, height = 10;

   public void paintComponent(final Graphics g) { // <---- using repaint method
      ActionListener taskPerformer = new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            g.setColor(Color.red);
            g.drawOval(x, y, width, height);
            g.fillOval(x, y, width, height);
            x++;
            y++;
            width++;
            height++;
         }
      };
      new Timer(100, taskPerformer).start();
   }
}

class mainClass {
   mainClass() {
      buildGUI();
   }

   public void buildGUI() {
      JFrame fr = new JFrame("Moving Objects");
      movingObjects obj = new movingObjects();
      fr.add(obj);
      fr.setVisible(true);
      fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      fr.setSize(1300, 700);
   }

   public static void main(String args[]) {
      new mainClass();
   }
}

Upvotes: 1

Views: 2060

Answers (1)

Mark Peters
Mark Peters

Reputation: 81154

Don't try to delay the actual painting. The component needs to be painted when it is asked to be painted.

Instead, use your timer to modify some state in MovingObjects. In your case the state you want to change is x, y, width and height. When your timer fires, increment those values and call repaint().

Then in your paintComponents method, you would just use those values to paint the component

public void paintComponent(Graphics g) {
  g.setColor(Color.red);
  g.drawOval(x,y,width,height);
  g.fillOval(x,y,width,height);
}

Edit

Not sure what you're having trouble with, but calling repaint() is not difficult:

ActionListener taskPerformer=new ActionListener() {
   public void actionPerformed(ActionEvent ae) {
      x++;
      y++;
      width++;
      height++;
      repaint();
   }
};
new Timer(100,taskPerformer).start();

Upvotes: 2

Related Questions