用Java写一个跳动的爱心代码
时间: 2024-12-14 17:14:24 浏览: 11
在Java中,制作一个跳动的爱心代码通常涉及到动画效果,可以使用Swing库或者JavaFX来实现。这里我将提供一个简单的Swing框架下的心形按钮,它会随着鼠标悬停而改变大小,模拟“跳动”感觉:
```java
import javax.swing.*;
import java.awt.geom.Ellipse2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class BouncingHeartButton extends JButton {
private int initialSize = 50;
private int maxSize = 80;
private boolean isBouncing = false;
public BouncingHeartButton() {
super(new JLabel(new Ellipse2D.Double(-initialSize / 2, -initialSize / 2, initialSize, initialSize)));
setBorderPainted(false);
setContentAreaFilled(false);
// 添加鼠标事件监听器
addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
startBounce();
}
@Override
public void mouseExited(MouseEvent e) {
stopBounce();
}
});
}
private void startBounce() {
if (!isBouncing) {
SwingUtilities.invokeLater(() -> {
new Timer(50, this::bounce).start();
isBouncing = true;
});
}
}
private void bounce() {
int newSize = initialSize + (Math.random() * (maxSize - initialSize));
setSize(newSize, newSize);
if (newSize > maxSize) {
startBounce();
} else {
setSize(initialSize, initialSize);
}
}
private void stopBounce() {
isBouncing = false;
Timer timer = (Timer) getAncestorOfClass(Timer.class);
if (timer != null) {
timer.stop();
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Bouncing Heart Button");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new BouncingHeartButton());
frame.pack();
frame.setVisible(true);
}
}
```
这个代码会创建一个心形按钮,当鼠标滑过按钮时,按钮会随机变大然后回到初始大小,给人一种跳动的效果。注意这只是一个基本示例,实际的“跳动”效果可能需要更复杂的算法来控制频率和幅度。
阅读全文