用Java写出以离散的点显示自己的姓名的程序
时间: 2024-05-02 18:22:26 浏览: 36
可以使用Java中的Graphics2D类和JPanel类来实现在窗口中以离散的点显示自己的姓名。具体代码如下:
```
import javax.swing.*;
import java.awt.*;
public class NameDisplay extends JPanel {
private String name = "Your Name";
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
Font font = new Font("Monospaced", Font.PLAIN, 15);
g2d.setFont(font);
g2d.setColor(Color.BLACK);
FontMetrics fontMetrics = g2d.getFontMetrics();
int nameWidth = fontMetrics.stringWidth(name);
int nameHeight = fontMetrics.getHeight();
int x0 = 50; // 起点x坐标
int y0 = 50; // 起点y坐标
int d = 10; // 点的直径
int dx = nameWidth / d;
int dy = nameHeight / d;
for (int i = 0; i < name.length(); i++) {
int x = x0 + i * dx;
for (int j = 0; j < nameHeight; j += dy) {
int y = y0 + j;
g2d.fillOval(x, y, d, d);
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Name Display");
frame.add(new NameDisplay());
frame.setSize(500, 200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
```
将代码保存为NameDisplay.java并编译执行即可在窗口中看到以离散的点显示出自己的姓名。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)