java如何画圆
使用 Java 绘制圆的方法
在 Java 中,可以通过 Graphics 或 Graphics2D 类绘制圆形。以下是几种常见的方法:
使用 drawOval 方法
Graphics 类提供了 drawOval 方法,可以绘制一个空心圆。需要指定圆的左上角坐标和宽度、高度。

import javax.swing.*;
import java.awt.*;
public class DrawCircle extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawOval(50, 50, 100, 100); // 参数:x, y, width, height
}
public static void main(String[] args) {
JFrame frame = new JFrame("Draw Circle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DrawCircle());
frame.setSize(200, 200);
frame.setVisible(true);
}
}
使用 fillOval 方法
Graphics 类的 fillOval 方法可以绘制一个实心圆。

import javax.swing.*;
import java.awt.*;
public class FillCircle extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillOval(50, 50, 100, 100); // 参数:x, y, width, height
}
public static void main(String[] args) {
JFrame frame = new JFrame("Fill Circle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new FillCircle());
frame.setSize(200, 200);
frame.setVisible(true);
}
}
使用 Graphics2D 绘制更复杂的圆
Graphics2D 提供了更多绘制选项,例如设置线条宽度、颜色等。
import javax.swing.*;
import java.awt.*;
public class DrawCircleWithGraphics2D extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
g2d.setStroke(new BasicStroke(3)); // 设置线条宽度
g2d.drawOval(50, 50, 100, 100);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Draw Circle with Graphics2D");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DrawCircleWithGraphics2D());
frame.setSize(200, 200);
frame.setVisible(true);
}
}
使用数学公式绘制圆
如果需要更精确地控制圆的绘制,可以使用数学公式计算圆的点。
import javax.swing.*;
import java.awt.*;
public class DrawCircleWithFormula extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int centerX = 100;
int centerY = 100;
int radius = 50;
for (int angle = 0; angle < 360; angle++) {
double radians = Math.toRadians(angle);
int x = (int) (centerX + radius * Math.cos(radians));
int y = (int) (centerY + radius * Math.sin(radians));
g.drawLine(x, y, x, y);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Draw Circle with Formula");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DrawCircleWithFormula());
frame.setSize(200, 200);
frame.setVisible(true);
}
}
以上方法可以根据需求选择适合的方式绘制圆。






