java编写炫酷圣诞树代码
时间: 2023-12-27 20:24:42 浏览: 93
html+css实现圣诞树效果!
以下是一个简单的Java代码示例,用于绘制一个炫酷的圣诞树:
```java
import javax.swing.*;
import java.awt.*;
public class MyPanel extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
drawTree(g, getWidth() / 2, getHeight() - 50, 100, 200);
}
private void drawTree(Graphics g, int x, int y, int width, int height) {
g.setColor(new Color(34, 139, 34)); // 设置树的颜色为绿色
// 绘制树干
int trunkWidth = width / 5;
int trunkHeight = height / 5;
int trunkX = x - trunkWidth / 2;
int trunkY = y - height;
g.fillRect(trunkX, trunkY, trunkWidth, trunkHeight);
// 绘制树冠
int[] triangleX = {x - width / 2, x + width / 2, x};
int[] triangleY = {y, y, y - height};
g.fillPolygon(triangleX, triangleY, 3);
// 绘制装饰品
g.setColor(Color.RED); // 设置装饰品的颜色为红色
g.fillOval(x - 10, y - height - 30, 20, 20); // 绘制一个圆形装饰品
g.setColor(Color.YELLOW); // 设置装饰品的颜色为黄色
g.fillRect(x - 5, y - height - 40, 10, 40); // 绘制一个长方形装饰品
}
}
public class MyFrame extends JFrame {
public MyFrame() {
setTitle("炫酷圣诞树");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setLocationRelativeTo(null);
MyPanel panel = new MyPanel();
add(panel);
setVisible(true);
}
}
public class Main {
public static void main(String[] args) {
new MyFrame();
}
}
```
阅读全文