更新时间:2022-10-21 09:52:45
进口java.awt中的*。
java.awt.event中导入*。
java.awt.image中导入*。
进口的javax.swing *。
进口了java.util.Random;类ImageBlinker扩展JComponent的{ BufferedImage的图像;
布尔showImage;
INT X = -1;
诠释Y = -1;
随机ř; ImageBlinker(){
//把你的图像读取code在这里..
图像=新的BufferedImage(32,32,BufferedImage.TYPE_INT_ARGB);
图形G = image.createGraphics();
g.setColor(Color.ORANGE);
g.fillOval(0,0,32,32);
// END - 图像读 R =新的随机();
ActionListener的听众=新的ActionListener(){
公共无效的actionPerformed(ActionEvent的AE){
如果(形象!= NULL){
如果(!showImage){
INT W = image.getWidth();
INT H = image.getHeight();
INT RX =的getWidth() - 瓦;
INT RY =的getHeight() - H;
如果(RX -1个和放大器;&安培; RY -1个){
X = r.nextInt(RX);
Y = r.nextInt(RY);
}
}
!showImage = showImage;
重绘();
}
}
};
定时器定时器=新定时器(600,监听器);
timer.start(); 集preferredSize(新尺寸(150,100));
JOptionPane.showMessageDialog(null,则此);
timer.stop();
} 公共无效的paintComponent(图形G){
g.setColor(Color.BLUE);
g.fillRect(0,0,的getWidth(),的getHeight());
如果(showImage&安培;&安培;!图像= NULL){
g.drawImage(图像,X,Y,这一点);
}
} 公共静态无效的主要(字串[] args){
SwingUtilities.invokeLater(Runnable的新(){
公共无效的run(){
新ImageBlinker();
}
});
}
}
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();
}
});
}
}