现在是一名高级程序员,请你用Java帮我写一个程序,要求画两个火柴人分别在左右两边,左边的人向右边的人发送一个爱心,右边的人接受到爱心之后,也向左边的人发送一个比较大的爱心,上面有感谢兄弟们的祝福这几个字,
时间: 2024-03-11 13:43:36 浏览: 103
好的,以下是Java代码:
```java
import java.awt.*;
import javax.swing.*;
public class LoveFrame extends JFrame {
private static final long serialVersionUID = 1L;
private int x1, y1, x2, y2;
private Image leftImage, rightImage, heartImage, bigHeartImage;
private boolean leftClicked, rightClicked;
public LoveFrame() {
setTitle("火柴人传递爱心");
setSize(800, 600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
x1 = 100;
y1 = 200;
x2 = 500;
y2 = 200;
leftImage = new ImageIcon(getClass().getResource("/left.png")).getImage();
rightImage = new ImageIcon(getClass().getResource("/right.png")).getImage();
heartImage = new ImageIcon(getClass().getResource("/heart.png")).getImage();
bigHeartImage = new ImageIcon(getClass().getResource("/bigheart.png")).getImage();
addMouseListener(new LoveListener());
setVisible(true);
}
private class LoveListener extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
if (x >= x1 && x <= x1 + leftImage.getWidth(null) && y >= y1 && y <= y1 + leftImage.getHeight(null)) {
leftClicked = true;
repaint();
}
if (x >= x2 && x <= x2 + rightImage.getWidth(null) && y >= y2 && y <= y2 + rightImage.getHeight(null)) {
rightClicked = true;
repaint();
}
}
}
public void paint(Graphics g) {
super.paint(g);
g.drawImage(leftImage, x1, y1, null);
g.drawImage(rightImage, x2, y2, null);
if (leftClicked) {
g.drawImage(heartImage, x1 + leftImage.getWidth(null) / 2 - heartImage.getWidth(null) / 2, y1 - heartImage.getHeight(null), null);
try {
Thread.sleep(1000); //等待1秒钟
} catch (InterruptedException e) {
e.printStackTrace();
}
g.drawImage(bigHeartImage, x2 + rightImage.getWidth(null) / 2 - bigHeartImage.getWidth(null) / 2, y2 - bigHeartImage.getHeight(null), null);
g.setFont(new Font("黑体", Font.BOLD, 30));
g.setColor(Color.WHITE);
g.drawString("感谢兄弟们的祝福", x2 + rightImage.getWidth(null) / 2 - 120, y2 - bigHeartImage.getHeight(null) - 50);
leftClicked = false;
rightClicked = false;
}
if (rightClicked) {
g.drawImage(heartImage, x2 + rightImage.getWidth(null) / 2 - heartImage.getWidth(null) / 2, y2 - heartImage.getHeight(null), null);
}
}
public static void main(String[] args) {
new LoveFrame();
}
}
```
这个程序使用 Java Swing 组件绘制了两个火柴人,并在它们的中间绘制了一个空心的圆形,模拟两个人之间传递爱心的过程。当左边的火柴人被点击时,会出现一个爱心,并向右边的火柴人发送一个实心的爱心。当右边的火柴人接受到爱心时,会出现一个比较大的爱心,上面有“感谢兄弟们的祝福”这几个字。
阅读全文