java用户图形界面心形线的代码
时间: 2024-04-30 18:21:44 浏览: 14
以下是一个简单的 Java 心形线的图形界面代码:
```java
import javax.swing.*;
import java.awt.*;
public class HeartLine extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setStroke(new BasicStroke(3));
g2d.setColor(Color.RED);
int x = 75;
int y = 150;
g2d.drawLine(x, y, x, y);
for (double t = 0; t <= Math.PI; t += 0.01) {
int x1 = (int) (16 * Math.pow(Math.sin(t), 3));
int y1 = (int) (13 * Math.cos(t) - 5 * Math.cos(2 * t) - 2 * Math.cos(3 * t) - Math.cos(4 * t));
g2d.drawLine(x + x1, y - y1, x + x1, y - y1);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Heart Line");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new HeartLine());
frame.setSize(200, 300);
frame.setVisible(true);
}
}
```
代码使用 `JPanel` 继承类创建了一个绘制心形线的图形界面。在 `paintComponent` 方法中,使用 `Graphics2D` 对象绘制心形线,同时设置线条粗细和颜色。最后,在 `main` 方法中创建一个 `JFrame` 对象并将 `HeartLine` 对象添加到其中,设置窗口大小并显示。