Graphics2D Quiz: draw circle - Java 2D Graphics

Java examples for 2D Graphics:Ellipse

Introduction

Create an application that draws a circle.

Demo Code

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JFrame {
  public Main() {
    super("Circle");
    setSize(350, 250);//from  www.  jav a 2  s . c o m
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    CirclePanel cp = new CirclePanel();
    add(cp);
    setVisible(true);
  }

  public static void main(String[] arguments) {
      Main dc = new Main();
  }
}

class CirclePanel extends JPanel {
  int radius, x, y;
  Color color;

  public CirclePanel() {
    super();
    radius = 100;
    x = 110;
    y = 110;
    color = Color.blue;
  }

  public void paintComponent(Graphics comp) {
    Graphics2D comp2D = (Graphics2D) comp;
    comp2D.setColor(Color.white);
    comp2D.fillRect(0, 0, getSize().width, getSize().height);
    comp2D.setColor(color);
    Ellipse2D.Float circle = new Ellipse2D.Float(x, y, radius, radius);
    comp2D.fill(circle);
  }
}

Related Tutorials