java 如何画圆
使用 Java 绘制圆形的方法
使用 Graphics 类绘制圆形
Java 的 Graphics 类提供了 drawOval 方法,可以在 Swing 组件上绘制圆形。以下是一个简单的示例代码:
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);
}
}
使用 Graphics2D 绘制圆形
Graphics2D 是 Graphics 的子类,提供了更丰富的绘图功能,可以设置线条粗细、颜色等属性:

import javax.swing.*;
import java.awt.*;
public class DrawCircle2D 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 DrawCircle2D());
frame.setSize(200, 200);
frame.setVisible(true);
}
}
填充圆形
如果需要填充圆形,可以使用 fillOval 方法:

import javax.swing.*;
import java.awt.*;
public class FillCircle extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillOval(50, 50, 100, 100);
}
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);
}
}
使用 Shape 接口绘制圆形
Shape 接口提供了更灵活的绘图方式,可以结合 Ellipse2D 类绘制圆形:
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Ellipse2D;
public class DrawCircleShape extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
Ellipse2D circle = new Ellipse2D.Double(50, 50, 100, 100);
g2d.draw(circle);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Draw Circle with Shape");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DrawCircleShape());
frame.setSize(200, 200);
frame.setVisible(true);
}
}
使用 JavaFX 绘制圆形
如果使用 JavaFX,可以通过 Circle 类实现:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
public class DrawCircleFX extends Application {
@Override
public void start(Stage primaryStage) {
Circle circle = new Circle(100, 100, 50);
circle.setFill(Color.GREEN);
StackPane root = new StackPane();
root.getChildren().add(circle);
Scene scene = new Scene(root, 200, 200);
primaryStage.setTitle("Draw Circle with JavaFX");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
以上方法涵盖了从基础的 Swing 绘图到 JavaFX 的多种实现方式,可以根据项目需求选择合适的方法。






