Results 1 to 11 of 11
  1. #1
    lordbob75 is offline Member
    Join Date
    Nov 2008
    Location
    Earth
    Posts
    14
    Rep Power
    0

    Angry Animation failure...

    Hello all,

    After taking almost two years of Java at my school (though only half of the first year was really taught....), I am trying to make my final project.

    My goal is to create a defense style game, sort of like Defend your Castle and such. Without throwing the stick figures though.

    Anyways, I am trying to learn how to animate. We sort of learned this, but I never got it. I am still having A LOT of trouble with it. I can draw images, though in my last program that REFUSED to work for me...
    What I need help with is the actual animation. I can make everything else, but animation has me stumped. I can get a rectangle to move across the screen, but that's about it, and I don't really understand it.
    I have looked for weeks, and still not found a good tutorial that shows me VERY SIMPLY how to do this.

    For clarification, I would really prefer to use Threads in either JApplet, or Applet, though ANY help would be greatly appreciated.

    ~Lordbob

  2. #2
    Mr.Beans's Avatar
    Mr.Beans is offline Senior Member
    Join Date
    Apr 2009
    Location
    Virginia Beach, Virginia
    Posts
    149
    Rep Power
    0

    Default

    Create an AnimatedImage class. The update the animated image every so often (ie every frame). The class should have an array of images (the animation) and should iterate through them. Show the first image in the animation, then the second .... the last, then the first again. Make it a continuous cycle.

  3. #3
    lordbob75 is offline Member
    Join Date
    Nov 2008
    Location
    Earth
    Posts
    14
    Rep Power
    0

    Default

    I understand the concept Mr. Beans, I thought that I said that....

    What I don't understand is HOW to do it. I have searched and searched and tried many ways, but none of them worked for me, or I just didn't understand.

    Thanks for the reply,

    ~Lordbob

  4. #4
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    either JApplet, or Applet
    JApplet/Swing is much easier to work with. Applet/AWT animation requires a different, more complicated technique.
    Here's an example that should help you sort things out.
    Java Code:
    //  <applet code="AnimTest" width="400" height="400"></applet>
    //  run at the prompt with: >appletviewer AnimTest.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class AnimTest extends JApplet {
        AnimPanel animPanel = new AnimPanel();
        Animator animator = new Animator(animPanel);
    
        public void init() {
            add(animPanel);
            add(getUIPanel(), "Last");
        }
    
        private JPanel getUIPanel() {
            String[] ids = { "start", "stop" };
            ActionListener al = new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    String id = e.getActionCommand();
                    if(id.equals("start")) {
                        animator.start();
                    }
                    if(id.equals("stop")) {
                        animator.stop();
                    }
                }
            };
            JPanel panel = new JPanel();
            for(int i = 0; i < ids.length; i++) {
                JButton button = new JButton(ids[i]);
                button.setActionCommand(ids[i]);
                button.addActionListener(al);
                panel.add(button);
            }
            return panel;
        }
    
        public void stop() {
            animator.stop();
        }
    }
    
    class AnimPanel extends JPanel {
        Rectangle rect = new Rectangle(100,100,200,125);
    
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setPaint(Color.red);
            g2.drawRect(0, 0, getWidth()-1, getHeight()-1);
            g2.setPaint(Color.blue);
            g2.draw(rect);
        }
    
        public void moveRect(int dx, int dy) {
            rect.translate(dx, dy);
            repaint();
        }
    }
    
    class Animator implements Runnable {
        AnimPanel component;
        Thread thread;
        boolean running = false;
        long delay = 100L;
        int dx = 3;
        int dy = 2;
    
        public Animator(AnimPanel ap) {
            component = ap;
        }
    
        public void run() {
            while(running) {
                try {
                    Thread.sleep(delay);
                } catch(InterruptedException e) {
                    stop();
                }
                advance();
            }
        }
    
        private void advance() {
            checkBounds();
            component.moveRect(dx, dy);
        }
    
        private void checkBounds() {
            int w = component.getWidth();
            int h = component.getHeight();
            Rectangle r = component.rect;
            if(r.x + dx < 0 || r.x + r.width + dx > (w-1)) {
                dx *= -1;
            }
            if(r.y + dy < 0 || r.y + r.height + dy > (h-1)) {
                dy *= -1;
            }
        }
    
        public void start() {
            if(!running) {
                running = true;
                thread = new Thread(this);
                thread.setPriority(Thread.NORM_PRIORITY);
                thread.start();
            }
        }
    
        public void stop() {
            running = false;
            if(thread != null) {
                thread.interrupt();
            }
            thread = null;
        }
    }

  5. #5
    lordbob75 is offline Member
    Join Date
    Nov 2008
    Location
    Earth
    Posts
    14
    Rep Power
    0

    Default

    Hardwired, thank you for the code. I don't quite understand some of it though...

    Thanks for the responses so far, but as I said in my first post, I can get simple animation to work. What is need is how to animate a set of images (sprite?).

    Here is what I know how to do:
    Java Code:
    import java.applet.Applet;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Image;
    
    @SuppressWarnings("serial")
    public class Animate extends Applet implements Runnable
    {
    	private Graphics buffer;
    	private Image bufferImage;
    	Thread runner;
    	Graphics2D g2;
    	int counter = 0;
    	int x= 0, y =0;
    	Image boom1;
    	
    	public void init()
    	{
    		bufferImage = createImage(900,500);
    		buffer = bufferImage.getGraphics();
    	}
    
    	public void start()
    	{
    		runner = new Thread(this);
    		runner.start();
    	}
    	
    	public void run()
    	{
    		while (runner!= null)
    		{	//All commands to be animated go here
    			buffer.setColor(Color.white);
    			buffer.fillRect(0, 0, 1000, 1000);
    			buffer.setColor(Color.black);
    			
    			System.out.println(counter);
    			counter++;
    			x++;
    			y++;
    			repaint();
    			
    			try
    			{
    				Thread.sleep(100);
    			}
    			catch (InterruptedException e)
    			{
    				stop();
    			}
    	    }
    	}
    	
    	public void paint(Graphics g)
    	{
    		Graphics2D g2 = (Graphics2D)g;
    		setSize(500,500);
    		
    		buffer.fillRect(x,y,10,10);
    		buffer.drawImage(boom1, 100, 100, 100, 100, this);
    		
    		g2.drawImage(bufferImage, 0, 0, null);
    	}
    }
    ~Lordbob

  6. #6
    lordbob75 is offline Member
    Join Date
    Nov 2008
    Location
    Earth
    Posts
    14
    Rep Power
    0

    Default

    Hey guys, thanks for the replies so far, but I really need help with this. I am at a loss as to what to do.

    I need to have this program done in about a week and a half too..... Any and all help is greatly appreciated...

    ~Lordbob

  7. #7
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    Java Code:
    //  <applet code="AnimateApplet" width="400" height="400"></applet>
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.image.BufferedImage;
    
    public class AnimateApplet extends Applet implements Runnable
    {
        AnimatePanel view;
        Thread runner;
        int counter = 0;
    
        public void init()
        {
            int w = 100, h = 100,
            type = BufferedImage.TYPE_INT_RGB;
            BufferedImage image = new BufferedImage(w, h, type);
            Graphics2D g2 = image.createGraphics();
            g2.setPaint(Color.blue);
            g2.fillRect(0,0,w,h);
            g2.setPaint(Color.red);
            g2.fillOval(w/4,h/4,w/2,h/2);
            g2.dispose();
            System.out.println("default layout manager for Applet = " +
                                getLayout().getClass().getName());
            view = new AnimatePanel(image);
            setLayout(new BorderLayout());
            add(view);
            resize(500,500);
        }
    
        public void start()
        {
            runner = new Thread(this);
            runner.start();
        }
    
        public void stop()
        {
            if(runner != null)
            {
                runner.interrupt();
            }
            runner = null;
        }
    
        public void run()
        {
            while (runner!= null)
            {
                view.step();
                System.out.println(counter);
                counter++;
    
                try
                {
                    Thread.sleep(100);
                }
                catch (InterruptedException e)
                {
                    stop();
                }
            }
        }
    }
    
    class AnimatePanel extends Panel
    {
        private Graphics bufferGpx;
        private Image bufferImage;
        int x = 0, y = 0;
        Image boom1;
    
        public AnimatePanel(Image image)
        {
            boom1 = image;
            System.out.println("calling \"createImage\" here returns " +
                                createImage(400,400));
        }
    
        public void paint(Graphics g)
        {
            if(bufferImage == null)
            {
                int w = getWidth();
                int h = getHeight();
                bufferImage = createImage(w, h);
                bufferGpx = bufferImage.getGraphics();
                bufferGpx.setColor(Color.white);
                int iw = bufferImage.getWidth(this);
                int ih = bufferImage.getHeight(this);
                bufferGpx.fillRect(0,0,iw,ih);
            }
            g.drawImage(bufferImage, 0, 0, null);
        }
    
        public void update(Graphics g)
        {
            paint(g);
        }
    
        public void step()
        {
            if(bufferImage == null) return;
            bufferGpx.setColor(Color.white);
            int iw = bufferImage.getWidth(this);
            int ih = bufferImage.getHeight(this);
            bufferGpx.fillRect(0,0,iw,ih);
            x++;
            y++;
            bufferGpx.drawImage(boom1, x, y, this);
            repaint();
        }
    }

  8. #8
    lordbob75 is offline Member
    Join Date
    Nov 2008
    Location
    Earth
    Posts
    14
    Rep Power
    0

    Default

    Hardwired, thank you for the code, but I don't really understand it...

    I know it is probably frustrating to hear this, as you guys know 10000 times more than I do. I am just a beginner and just don't get a lot of this.

    Can you explain how each method works?

    ~Lordbob

  9. #9
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    Can you explain how each method works?
    No. The way to learn when you have code that compiles and runs is:
    1 reconstruct it starting with a blank/new file. You do this by slowly building up the Applet a little bit at a time, compiling and running often to get the results you want in a way you can understand. In this case you could start with the Applet, its UIPanel, and a blank (maybe colored, simple) Panel added to the center section. Then begin working on loading/making an image for the Panel/graphic_component; drawing the image; changing its location, etc. Finally add the animation code.
    2 You can organize your class(es) as you like. Experiment, try different things to get what you want. The example code uses a separate Panel for the graphic component as opposed to your code in which the drawing was done in/on the Applet itself (with the applets Container paint method). Either way is okay if you can get the behavior you want.
    3 the basic idea is to configure the drawing/graphic component so tht it can draw itself at any time, egs, when restored, resized, repainted by the system or by user-initiated or app-initiated (animation code) events. Then have your event/animation code make changes to the variables in the graphic component, here, the variables x and y, that control the animation. However you can get this to work is an okay place to start.
    4 start simple and build slowly so you can understand what you are doing.

  10. #10
    lordbob75 is offline Member
    Join Date
    Nov 2008
    Location
    Earth
    Posts
    14
    Rep Power
    0

    Default

    OK thanks Hardwired. Unfortunately I don't have time to do that for this project, but I will when school is out, so I will do it then.

    As for what I need to do:
    Can you show me a simple way to animate a gif? I have, say 5, images that make an animation sprite. I want to draw them all separately (like in an array) and draw them in sequence to animate it. For example, I want a stick figure with 5 frames of animation (as separate images) to walk across the screen.

    Is there any simple way to do that? I have found multiple tutorials, but none of them made sense to me, nor have I gotten any to work with my own images...

    ~Lordbob

  11. #11
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    Java Code:
    //  <applet code="ImageWalk" width="500" height="200"></applet>
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    
    public class ImageWalk extends JApplet implements Runnable {
        BufferedImage[] images;
        int index = 0;
        int x = 0, y = 100;
        Thread thread;
    
        public void init() {
            images = getImages();
        }
    
        public void paint(Graphics g) {
            super.paint(g);
            g.setColor(Color.blue);
            g.drawRect(0,0,getWidth()-1,getHeight()-1);
            g.drawImage(images[index], x, y, this);
        }
    
        public void start() {
            thread = new Thread(this);
            thread.setPriority(Thread.NORM_PRIORITY);
            thread.start();
        }
    
        public void stop() {
            if(thread != null) {
                thread.interrupt();
            }
            thread = null;
        }
    
        public void run() {
            long delay = 1000;
            do {
                try {
                    Thread.sleep(delay);
                } catch(InterruptedException e) {
                    break;
                }
                x += images[index].getWidth();
                index = (index +1) % images.length;
                repaint();
            } while(x < getWidth());
            System.out.println("x = " + x);
        }
    
        private BufferedImage[] getImages() {
            Color[] colors = {
                Color.red, Color.green, Color.blue, Color.yellow, Color.orange
            };
            images = new BufferedImage[colors.length];
            int w = 50, h = 75, type = BufferedImage.TYPE_INT_RGB;
            for(int i = 0; i < images.length; i++) {
                images[i] = new BufferedImage(w, h, type);
                Graphics2D g2 = images[i].createGraphics();
                g2.setBackground(Color.white);
                g2.clearRect(0,0,w,h);
                g2.setPaint(colors[i]);
                g2.drawRect(0,0,w-1,h-1);
                g2.drawString(String.valueOf(i+1), w/2, h/2);
            }
            return images;
        }
    }

Similar Threads

  1. Animation with Animated GIF
    By JavaBean in forum Java 2D
    Replies: 3
    Last Post: 06-04-2011, 04:26 PM
  2. Animation Synchronization
    By dreadrocksean in forum Advanced Java
    Replies: 5
    Last Post: 08-08-2008, 02:56 AM
  3. Demonstration of animation in SWT
    By Java Tip in forum SWT
    Replies: 0
    Last Post: 06-28-2008, 09:27 PM
  4. GUI Animation
    By serfster in forum New To Java
    Replies: 2
    Last Post: 06-11-2008, 03:37 AM
  5. Replies: 1
    Last Post: 03-14-2008, 02:51 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
  •