簡體   English   中英

如何使圖像在隨機位置閃爍?

[英]How to make an image blink in a random position?

我在JApplet有一個圖像,我希望它以隨機位置顯示。 1秒后它將消失,並在另一個隨機位置再次出現。

如何實現“隨機閃爍”?

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

為了我的錢,我將Image放在ImageIcon中,將ImageIcon放在JLabel中,然后使用Swing Timer和Random對象將JLabel隨機移動。 您必須將其移動到一個布局已設置為null的容器中(contentPane會這樣做),並且必須將JLabel的大小指定為其preferredSize才能起作用。

圖像閃爍器

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM