本文介绍了如何使图像在随机位置闪烁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 JApplet 中有一个图像,我希望它出现在随机位置.它会在 1 秒后消失并在另一个随机位置再次出现.

I have an image inside the JApplet and I want it to appear in a random position. It will disappear after 1 second and appear again, in another random position.

如何实现随机位置闪烁"?

How do I implement 'blinking in a random position'?

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.net.URL;

public class Random extends JApplet
{

 Image ball;

  public void init()
  {
    try
    {
        URL pic = new URL(getDocumentBase(), "ball.gif");
        ball = ImageIO.read(pic);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
   }

    public void paint(Graphics g)
    {
       if (ball != null)
      {
        g.drawImage(ball,50,50,50,50,this);
      }
    }
}

推荐答案

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import java.util.Random;

class ImageBlinker extends JComponent {

    BufferedImage image;
    boolean showImage;
    int x = -1;
    int y = -1;
    Random r;

    ImageBlinker() {
        // put your image reading code here..
        image = new BufferedImage(32,32,BufferedImage.TYPE_INT_ARGB);
        Graphics g = image.createGraphics();
        g.setColor(Color.ORANGE);
        g.fillOval(0,0,32,32);
        // END - image read

        r = new Random();
        ActionListener listener = new ActionListener(){
            public void actionPerformed(ActionEvent ae) {
                if (image!=null) {
                    if (!showImage) {
                        int w = image.getWidth();
                        int h = image.getHeight();
                        int rx = getWidth()-w;
                        int ry = getHeight()-h;
                        if (rx>-1 && ry>-1) {
                            x = r.nextInt(rx);
                            y = r.nextInt(ry);
                        }
                    }
                    showImage = !showImage;
                    repaint();
                }
            }
        };
        Timer timer = new Timer(600,listener);
        timer.start();

        setPreferredSize(new Dimension(150,100));
        JOptionPane.showMessageDialog(null, this);
        timer.stop();
    }

    public void paintComponent(Graphics g) {
        g.setColor(Color.BLUE);
        g.fillRect(0,0,getWidth(),getHeight());
        if (showImage && image!=null) {
            g.drawImage(image,x,y,this);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ImageBlinker();
            }
        });
    }
}

这篇关于如何使图像在随机位置闪烁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 21:49