可以改名字的圣诞树代码
时间: 2023-12-22 19:30:09 浏览: 29
以下是一个可以改名字的圣诞树代码的示例:
```java
import java.awt.*;
import javax.swing.*;
public class ChristmasTree extends JPanel {
private String name;
public ChristmasTree(String name) {
this.name = name;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
// 绘制树层
int treeWidth = 100;
int treeHeight = 150;
int x = getWidth() / 2 - treeWidth / 2;
int y = getHeight() - treeHeight;
g2d.setColor(new Color(34, 139, 34)); // 绿色
g2d.fillRect(x, y, treeWidth, treeHeight);
// 绘制树干
int trunkWidth = 20;
int trunkHeight = 30;
int trunkX = getWidth() / 2 - trunkWidth / 2;
int trunkY = getHeight() - trunkHeight - 10;
g2d.setColor(new Color(139, 69, 19)); // 棕色
g2d.fillRect(trunkX, trunkY, trunkWidth, trunkHeight);
// 绘制名字
g2d.setColor(Color.WHITE);
g2d.setFont(new Font("Arial", Font.BOLD, 20));
FontMetrics fm = g2d.getFontMetrics();
int nameWidth = fm.stringWidth(name);
int nameX = getWidth() / 2 - nameWidth / 2;
int nameY = getHeight() - treeHeight - trunkHeight - 20;
g2d.drawString(name, nameX, nameY);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Christmas Tree");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 400);
ChristmasTree tree = new ChristmasTree("Merry Christmas!");
frame.add(tree);
frame.setVisible(true);
}
}
```
你可以在`ChristmasTree`类的构造函数中传入不同的名字来改变圣诞树上显示的文字。运行代码后,将会显示一个带有指定名字的圣诞树。