Results 1 to 7 of 7
  1. #1
    ProGenius is offline Member
    Join Date
    Dec 2009
    Posts
    9
    Rep Power
    0

    Default Move objects with Timer

    Hi. I want to implement a Java Timer so I can move an object on the screen. Can anyone explain me what do I need to do in order to make the object move by increasing its x/y value using Timer?

    Thanks in advance.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    A very simple example can be seen here:
    Simple animation won't work

    Edit: a JFrame example:
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class SimpleSwingAnimation {
    
      private static final Dimension SIZE = new Dimension(600, 600);
    
      private static void createAndShowUI() {
        JFrame frame = new JFrame("SimpleSwingAnimation");
        frame.getContentPane().add(new AnimationPanel());
        frame.getContentPane().setPreferredSize(SIZE);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    
      public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
            createAndShowUI();
          }
        });
      }
    }
    
    @SuppressWarnings("serial")
    class AnimationPanel extends JPanel {
      private static final int RADIUS = 20;
      private static final int TIMER_DELAY = 20;
      private int  xPos = 10;
      private int yPos = 100;
    
      public AnimationPanel() {
        setBackground(Color.blue);
        javax.swing.Timer timer = new javax.swing.Timer(TIMER_DELAY, new ActionListener() {
          public void actionPerformed(ActionEvent arg0) {
            xPos++;
            yPos++;
            AnimationPanel.this.repaint();
          }
        });
        timer.start();
      }
      
      @Override
      // override a Swing JComponent's paintComponent, not the paint method
      protected void paintComponent(Graphics g) {
        super.paintComponent(g); // again to repaint the screen
        
        // set antialiasing rendering hints to smooth out the circle
        // this is not necessary but makes for prettier animation
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
            RenderingHints.VALUE_ANTIALIAS_ON);
        
        g.setColor(Color.red);
        g.fillOval(xPos  - RADIUS, yPos  - RADIUS, 2 * RADIUS, 2 * RADIUS);
      }
    }
    Last edited by Fubarable; 12-27-2009 at 02:36 AM. Reason: Code posted

  3. #3
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default

    A simpler way to do this is simply using loops, a call to Thread.sleep() and a buffered image. Using timer is probably a better way to do it, but requires knowledge of several more advanced concepts like event handling, interfaces, etc... Here is a quick example on how to move a ball around a screen:
    Java Code:
    package fun;
    
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.image.BufferedImage;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.JFrame;
    
    public class Main {
    
        public static void main(String[] args) {
            new Main();
        }
        JFrame window;
        BufferedImage img;
    
        public Main() {
            img = new BufferedImage(640, 480, BufferedImage.OPAQUE);
            window = new JFrame() {
    
                public void paint(Graphics g) {
                    g.drawImage(img, 0, 0, rootPane);
                }
            };
    
            window.setSize(640, 480);
            window.setLocationRelativeTo(null);
            window.setDefaultCloseOperation(window.EXIT_ON_CLOSE);
            window.setVisible(true);
            animate();
        }
    
        public void animate() {
            Graphics g = img.getGraphics();
            for (int i = 0, j = 20; i < 640; i += 10, j += 7) {
                g.setColor(Color.white);
                g.fillRect(0, 0, 640, 480);
                g.setColor(Color.red);
                g.fillOval(i, j, 20, 20);
                window.repaint();
                try {
                    Thread.sleep(500);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

  4. #4
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default

    Hey Fubarable, I started typing my post before you, I wasn't trying to say my idea was better than yours, I just didn't see your post 'til after I'd written mine :D

  5. #5
    Steve11235's Avatar
    Steve11235 is offline Senior Member
    Join Date
    Dec 2008
    Posts
    1,046
    Rep Power
    7

    Default

    Make sure you use the Swing javax.swing.Timer and not the java.util.Timer version. The Swing version runs on the Event Dispatch Thread, where all Swing code should run. The reason not to use a loop is that it ties up your application... Timer is also a nice way to handle dragging objects, rather than listening to many, many mouse movement events.

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by quad64bit View Post
    Hey Fubarable, I started typing my post before you, I wasn't trying to say my idea was better than yours, I just didn't see your post 'til after I'd written mine :D
    No problem as they show two different techniques. But because you posted your code though, I posted mine. ;) I like using a Swing Timer for simple animation since as the timer does all its background threading behind the scenes, you don't have to worry about what's happening on what thread. So to me, it's simpler.

    I also think that using BufferedImages is more advanced than drawing directly in the JPanel (perhaps due to the order that I learned them).

  7. #7
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default

    I also think that using BufferedImages is more advanced than drawing directly in the JPanel (perhaps due to the order that I learned them).
    Thanks and good point! I did it this way since the #1 thing people say when they have learned by drawing on the screen for animation is "Why is it flickering/tearing? How do I stop that? Damnit! :D".

    Also, everything you said about using timer is totally correct, and I agree. The method I posted is simply the way I figured out how to do it years ago, and makes for a quick no-frills animation. Thanks for providing your code, it is an excellent example :D

Similar Threads

  1. Help with Move Shape
    By romina in forum AWT / Swing
    Replies: 2
    Last Post: 12-09-2010, 03:25 AM
  2. How do you move a picture?
    By Addez in forum New To Java
    Replies: 6
    Last Post: 11-03-2009, 08:44 PM
  3. how can i move from Frame to another
    By the swan in forum AWT / Swing
    Replies: 2
    Last Post: 04-04-2009, 04:24 PM
  4. Replies: 1
    Last Post: 01-22-2009, 04:25 PM
  5. Replies: 0
    Last Post: 04-04-2008, 02:46 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •