我在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);
}
}
}
答案 0 :(得分:2)
为了我的钱,我将Image放在ImageIcon中,将ImageIcon放在JLabel中,然后使用Swing Timer和Random对象随机移动JLabel。您必须将其移动到容器(contentPane将执行)中,其布局已设置为null,并且您必须将JLabel的大小指定为其preferredSize才能使其正常工作。
答案 1 :(得分:2)
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();
}
});
}
}