在JPanel上随机移动图像

时间:2015-03-08 15:36:31

标签: java image swing

我使用BufferedImageJPanel上显示两张图片。但是,我希望在单击按钮时图像随机移动,并且只有在按下另一个按钮时才会停止。

如何让我的图像在面板上随机移动?

这是我的代码的一部分:

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

1 个答案:

答案 0 :(得分:1)

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

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

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