java满屏飘爱心代码
时间: 2023-08-24 18:08:09 浏览: 182
爱心飘落代码
以下是Java代码实现屏幕飘爱心效果:
```
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class LoveScreen extends JFrame {
private static final long serialVersionUID = 1L;
private static final int WIDTH = 800;
private static final int HEIGHT = 600;
private static final int HEART_SIZE = 30;
private static final int MAX_HEARTS = 50;
private List<Point> hearts;
public LoveScreen() {
super("Love Screen");
hearts = new ArrayList<Point>();
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel panel = new JPanel() {
private static final long serialVersionUID = 1L;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.setFont(new Font("Arial", Font.BOLD, HEART_SIZE));
for (Point p : hearts) {
g.drawString("\u2665", p.x, p.y);
}
}
};
Timer timer = new Timer(100, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (hearts.size() < MAX_HEARTS) {
Random random = new Random();
int x = random.nextInt(WIDTH - HEART_SIZE);
int y = random.nextInt(HEIGHT - HEART_SIZE);
hearts.add(new Point(x, y));
}
for (Point p : hearts) {
p.y += 5;
}
panel.repaint();
}
});
getContentPane().add(panel);
setVisible(true);
timer.start();
}
public static void main(String[] args) {
new LoveScreen();
}
}
```
运行代码后,屏幕上会随机飘动50个爱心。可以根据自己的需要修改爱心数量、大小、颜色等参数。
阅读全文