Методы создания Java Circle: Swing, JavaFX и Graphics2D

Чтобы создать круг в Java, вы можете использовать различные методы в зависимости от контекста и требований. Вот некоторые распространенные подходы:

  1. Использование встроенной библиотеки Java Swing:

    import javax.swing.*;
    import java.awt.*;
    public class CircleExample extends JPanel {
       @Override
       protected void paintComponent(Graphics g) {
           super.paintComponent(g);
           int centerX = getWidth() / 2;
           int centerY = getHeight() / 2;
           int radius = 50; // Adjust the radius as needed
           g.drawOval(centerX - radius, centerY - radius, 2 * radius, 2 * radius);
       }
       public static void main(String[] args) {
           JFrame frame = new JFrame("Circle Example");
           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           frame.setSize(300, 300);
           frame.add(new CircleExample());
           frame.setVisible(true);
       }
    }

    Этот код создает круг с помощью библиотеки Swing и рисует его на компоненте JPanel.

  2. Использование JavaFX:

    import javafx.application.Application;
    import javafx.scene.Group;
    import javafx.scene.Scene;
    import javafx.scene.paint.Color;
    import javafx.scene.shape.Circle;
    import javafx.stage.Stage;
    public class CircleExample extends Application {
       @Override
       public void start(Stage stage) {
           Group root = new Group();
           Scene scene = new Scene(root, 300, 300);
           Circle circle = new Circle(150, 150, 50); // Adjust the center and radius as needed
           circle.setFill(Color.TRANSPARENT);
           circle.setStroke(Color.BLACK);
           root.getChildren().add(circle);
           stage.setTitle("Circle Example");
           stage.setScene(scene);
           stage.show();
       }
       public static void main(String[] args) {
           launch(args);
       }
    }

    Этот код демонстрирует, как создать круг с помощью JavaFX и отобразить его в окне.

  3. Использование Graphics2D:

    import java.awt.*;
    import javax.swing.*;
    public class CircleExample extends JPanel {
       @Override
       protected void paintComponent(Graphics g) {
           super.paintComponent(g);
           Graphics2D g2d = (Graphics2D) g;
           int centerX = getWidth() / 2;
           int centerY = getHeight() / 2;
           int radius = 50; // Adjust the radius as needed
           g2d.drawOval(centerX - radius, centerY - radius, 2 * radius, 2 * radius);
       }
       public static void main(String[] args) {
           JFrame frame = new JFrame("Circle Example");
           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           frame.setSize(300, 300);
           frame.add(new CircleExample());
           frame.setVisible(true);
       }
    }

    Этот код использует класс Graphics2Dдля создания круга и его рисования на компоненте JPanel.