在JPanel上随机移动图像 [英] Randomly moving images on a JPanel

查看:51
本文介绍了在JPanel上随机移动图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 BufferedImage 在我的 JPanel 上显示两个图像.但是,我希望图像在单击按钮时沿随机方向移动,并且仅在按下另一个按钮时才停止.

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()
{
}
}

推荐答案

您随时可以查看此示例以获取灵感.

You can always check this example for inspiration.

基本上,它使用javax.swing.Timer来对动画进行步调.每当动物到达框架的边缘时,它都会反转其方向以反转.方向和速度是随机计算的,请根据您的需要进行调整:

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:

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();
                }
            }
        });
    }
}

这篇关于在JPanel上随机移动图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆