java如何打圆形
使用Graphics2D绘制圆形
在Java中,可以通过Graphics2D类绘制圆形。Graphics2D提供了drawOval和fillOval方法,分别用于绘制空心圆形和实心圆形。以下是示例代码:
import javax.swing.*;
import java.awt.*;
public class DrawCircle extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
// 绘制空心圆形
g2d.drawOval(50, 50, 100, 100);
// 绘制实心圆形
g2d.setColor(Color.RED);
g2d.fillOval(200, 50, 100, 100);
}
public static void main(String[] args) {
JFrame frame = new JFrame("绘制圆形");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DrawCircle());
frame.setSize(400, 200);
frame.setVisible(true);
}
}
使用JavaFX绘制圆形
JavaFX提供了Circle类,可以更方便地绘制圆形。以下是示例代码:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
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) {
Pane pane = new Pane();
// 绘制空心圆形
Circle circle1 = new Circle(100, 100, 50);
circle1.setFill(null);
circle1.setStroke(Color.BLUE);
circle1.setStrokeWidth(2);
// 绘制实心圆形
Circle circle2 = new Circle(200, 100, 50);
circle2.setFill(Color.RED);
pane.getChildren().addAll(circle1, circle2);
Scene scene = new Scene(pane, 300, 200);
primaryStage.setTitle("绘制圆形");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
使用AWT绘制圆形
如果只需要简单的图形绘制,可以使用AWT的Graphics类:

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class DrawCircleAWT extends Frame {
public DrawCircleAWT() {
setSize(300, 200);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public void paint(Graphics g) {
// 绘制空心圆形
g.drawOval(50, 50, 100, 100);
// 绘制实心圆形
g.setColor(Color.RED);
g.fillOval(200, 50, 100, 100);
}
public static void main(String[] args) {
DrawCircleAWT frame = new DrawCircleAWT();
frame.setVisible(true);
}
}
参数说明
在上述代码中,绘制圆形的方法通常需要以下参数:
x:圆形左上角的x坐标。y:圆形左上角的y坐标。width:圆形的宽度(直径)。height:圆形的高度(直径)。
对于Circle类,参数略有不同:
centerX:圆心的x坐标。centerY:圆心的y坐标。radius:圆的半径。






