0

I am using a BufferedImage to display two images on my JPanel. However, I want the images move in random directions when a button is clicked and should only stop when another button is pressed.

How do I make my images move randomly on the panel?

This is part of my code:

 private void getImages() {
    try {
         frogImage = ImageIO.read(new File ("C:\\OOP\\CyberPet\\src\\img\\frog.gif"));
         flyImage = ImageIO.read(new File ("C:\\OOP\\CyberPet\\src\\img\\fly.gif"));

         g = panel.getGraphics();

         g.drawImage(frogImage, 500, 25, 40, 40, null); //set position and size of the image
         g.drawImage(flyImage, 40, 40, 10, 10, null); //set position and size of the image
    } catch (IOException e) {
    }
}

public void actionPerformed(ActionEvent event) {
    getImages();
    if (event.getSource() == makeButton){  

         responseArea.setText(enterField.getText());
      }
      else if(event.getSource() == hungryButton){
      }
      else if(event.getSource() == resetButton){        
    }
}

public void draw()
{
}
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Kany West
  • 1
  • 2
  • 2
    1) For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete Verifiable Example) or [SSCCE](http://www.sscce.org/) (Short, Self Contained, Correct Example). 2) One way to get image(s) for an example is to hot link to images seen in [this Q&A](http://stackoverflow.com/q/19209650/418556). 3) A single blank line of white space in source code is all that is *ever* needed. Blank lines after `{` or before `}` are also typically redundant. 4) You've described a requirement or specification, but asked no question. What is your question? – Andrew Thompson Mar 08 '15 at 15:38
  • 2
    .. 5) `g = panel.getGraphics();` That never ends well. Whatever book/resource etc. you got that from, throw it away. A Java GUI must draw when requested to do so. 6) `} catch (IOException e) { }` Don't ignore exceptions. That should be `} catch (IOException e) { e.printStackTrace(); }` 7) Use a logical and consistent form of indenting code lines and blocks. The indentation is intended to make the flow of the code easier to follow! 8) `g.drawImage(frogImage, 500, 25, 40, 40, null);` A `JComponent` is an image observer, so that should be `g.drawImage(frogImage, 500, 25, 40, 40, panel);` – Andrew Thompson Mar 08 '15 at 15:42
  • @AndrewThompson, thanks for the feedback. My question is how do I make my images move randomly on my JPanel. I have already imported java.util.Random; – Kany West Mar 08 '15 at 15:43
  • 1
    Check out [Motion Using the Keyboard](https://tips4java.wordpress.com/2013/06/09/motion-using-the-keyboard/) for example of how this can be done. Of course the code doesn't do exactly what you want, but it should get you started in the right direction. – camickr Mar 08 '15 at 16:00
  • I have managed to catch my exception public void draw() { try { Thread.sleep(1000); } catch (InterruptedException event) { // TODO Auto-generated catch block event.printStackTrace(); } draw(); } } But still not able to display the images randomly on my panel. – Kany West Mar 08 '15 at 17:07
  • 1) Don't put code in comments where it is barely readable, instead [edit the question](http://stackoverflow.com/posts/28928256/edit)! 2) But post an MCVE like I advised over an hour ago. 3) `// TODO Auto-generated catch block` You do realize you're supposed to remove that comment once you do anything useful with the catch block, right? 4) Tip: Add @camickr (or whoever, the `@` is important) to notify the person of a new comment. – Andrew Thompson Mar 08 '15 at 17:28
  • 1
    @Andrew Thompson, I've got you now. Thanks! – Kany West Mar 08 '15 at 17:33

1 Answers1

2

You can always check this example for inspiration.

Basically, it uses a javax.swing.Timer to pace the animation. Whenever an animal reaches an edge of the frame, it will reverse its direction to go in reverse. The directions and speed are randomly computed, adjust these to your needs:

enter image description here

import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Random;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UnsupportedLookAndFeelException;

public class TestAnimationFlyAndFrog {
    private static final int NB_OF_IMAGES_PER_SECOND = 50;
    private static final int WIDTH = 800;
    private static final int HEIGHT = 600;
    private Random random = new Random();

    private double dxFrog;
    private double dyFrog;

    private double xFrog = WIDTH / 2;
    private double yFrog = HEIGHT / 2;

    private double dxFly;
    private double dyFly;

    private double xFly = WIDTH / 2;
    private double yFly = HEIGHT / 2;

    protected void initUI() throws MalformedURLException {
        final JFrame frame = new JFrame(TestAnimationFlyAndFrog.class.getSimpleName());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(null);
        final JLabel frog = new JLabel(new ImageIcon(new URL("http://www.iconshock.com/img_jpg/SUPERVISTA/animals/jpg/128/frog_icon.jpg")));
        frog.setSize(frog.getPreferredSize());
        final JLabel fly = new JLabel(new ImageIcon(new URL("http://www.iconshock.com/img_jpg/SUPERVISTA/animals/jpg/128/fly_icon.jpg")));
        fly.setSize(fly.getPreferredSize());
        frame.setMinimumSize(new Rectangle(frog.getPreferredSize()).union(new Rectangle(fly.getPreferredSize())).getSize());
        frame.add(frog);
        frame.add(fly);
        frame.setSize(WIDTH, HEIGHT);
        dxFrog = getNextSpeed() * (random.nextBoolean() ? 1 : -1);
        dyFrog = getNextSpeed() * (random.nextBoolean() ? 1 : -1);
        dxFly = getNextSpeed() * (random.nextBoolean() ? 1 : -1);
        dyFly = getNextSpeed() * (random.nextBoolean() ? 1 : -1);
        Timer t = new Timer(1000 / NB_OF_IMAGES_PER_SECOND, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                xFrog += dxFrog;
                yFrog += dyFrog;
                if (xFrog + frog.getWidth() > frame.getContentPane().getWidth()) {
                    xFrog = frame.getContentPane().getWidth() - frog.getWidth();
                    dxFrog = -getNextSpeed();
                } else if (xFrog < 0) {
                    xFrog = 0;
                    dxFrog = getNextSpeed();
                }
                if (yFrog + frog.getHeight() > frame.getContentPane().getHeight()) {
                    yFrog = frame.getContentPane().getHeight() - frog.getHeight();
                    dyFrog = -getNextSpeed();
                } else if (yFrog < 0) {
                    yFrog = 0;
                    dyFrog = getNextSpeed();
                }
                frog.setLocation((int) xFrog, (int) yFrog);
                xFly += dxFly;
                yFly += dyFly;
                if (xFly + fly.getWidth() > frame.getContentPane().getWidth()) {
                    xFly = frame.getContentPane().getWidth() - fly.getWidth();
                    dxFly = -getNextSpeed();
                } else if (xFly < 0) {
                    xFly = 0;
                    dxFly = getNextSpeed();
                }
                if (yFly + fly.getHeight() > frame.getContentPane().getHeight()) {
                    yFly = frame.getContentPane().getHeight() - fly.getHeight();
                    dyFly = -getNextSpeed();
                } else if (yFly < 0) {
                    yFly = 0;
                    dyFly = getNextSpeed();
                }
                fly.setLocation((int) xFly, (int) yFly);

            }
        });
        frame.setVisible(true);
        t.start();
    }

    private double getNextSpeed() {
        return 2 * Math.PI * (0.5 + random.nextDouble());
    }

    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException,
            UnsupportedLookAndFeelException {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                try {
                    new TestAnimationFlyAndFrog().initUI();
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }
}
Guillaume Polet
  • 47,259
  • 4
  • 83
  • 117