java视频版会动圣诞树代码
时间: 2024-12-25 12:11:50 浏览: 9
在Java中创建一个会动的圣诞树代码通常是通过Swing库或者JavaFX图形组件来实现的动画效果。以下是一个简单的例子,展示了如何使用Java Swing库创建一个简单的会动圣诞树:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MovingTree extends JFrame {
private int direction = 0; // 0 - up, 1 - right, 2 - down, 3 - left
public MovingTree() {
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
// 创建静态部分(树干)
JPanel trunk = new JPanel();
trunk.setBounds(50, 200, 70, 70);
trunk.setBackground(Color.BLACK);
add(trunk);
// 创建动态部分(树枝)
JPanel branches = new JPanel(new FlowLayout());
for (int i = 0; i < 5; i++) {
JPanel branch = new JPanel();
branch.setBounds(50 + i * 70, 150 + direction * i * 20, 50, 20);
branch.setBackground(Color.GREEN);
branch.setSize(branch.getPreferredSize());
branches.add(branch);
}
add(branches);
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
switch (direction) {
case 0: direction = 1; break;
case 1: direction = 2; break;
case 2: direction = 3; break;
case 3: direction = 0; break;
}
branches.removeAll();
for (JPanel branch : branches) {
branch.setLocation(50 + direction * branches.getComponentCount() * 70,
150 + direction * branches.getComponentCount() * 20);
branch.setSize(branch.getPreferredSize());
branches.add(branch);
}
revalidate(); // 更新布局
}
};
Timer timer = new Timer(500, listener); // 每隔半秒改变方向
timer.start();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new MovingTree().setVisible(true));
}
}
```
这个程序中,一个静态的树干和五片动态的绿色分支组成了一棵圣诞树。使用了一个定时器每半秒改变`direction`,使得树枝沿着上、右、下、左四个方向移动。
阅读全文