java 实现一个动态闪烁的丘比特
时间: 2024-01-23 13:01:53 浏览: 22
下面是一个简单的Java代码示例,可以实现一个动态闪烁的丘比特图片。
```
import java.awt.*;
import javax.swing.*;
public class DynamicCupid extends JPanel implements Runnable {
private Image cupidImage;
private boolean isBlinking = false;
public DynamicCupid() {
cupidImage = new ImageIcon("cupid.png").getImage();
Thread thread = new Thread(this);
thread.start();
}
public void run() {
while (true) {
try {
Thread.sleep(500); // 闪烁间隔为0.5秒
} catch (InterruptedException e) {
e.printStackTrace();
}
isBlinking = !isBlinking;
repaint();
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (isBlinking) {
g.drawImage(cupidImage, 0, 0, null);
} else {
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Dynamic Cupid");
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DynamicCupid());
frame.setVisible(true);
}
}
```
这段代码创建了一个继承自JPanel的DynamicCupid类,在类的构造方法中加载了一个丘比特图片,并启动了一个线程来实现闪烁效果。在run方法中,通过调用repaint方法来触发paintComponent方法的调用,从而实现图片的闪烁。在paintComponent方法中,根据isBlinking变量的值来决定绘制丘比特图片还是绘制一个白色背景。最后,在main方法中创建了一个JFrame窗口,并将DynamicCupid对象添加到窗口中显示出来。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)