Raptrex
Raptrex

Reputation: 4105

Java making a drawCircle method calling drawOval

I need to make a drawCircle method that looks like

public void drawCircle(int x, int y, int radius)

that draws a circle with that center and radius. The drawCircle method needs to call drawOval. I am not sure how I can call drawOval from my drawCircle method without passing Graphics to it. Is this possible?

Heres what I have:

import java.awt.*;   
import javax.swing.*;

class test
{
    public static void main(String[] args)
    {
        JFrame frame = new JFrame("test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.getContentPane().add(new MyPanel());
        frame.pack();
        frame.setVisible(true);
    }
}
class MyPanel extends JPanel
{

    MyPanel()
    {
        setBackground(Color.WHITE);
        setPreferredSize(new Dimension(250,250));
    }

    public void paintComponent(Graphics page)
    {
        super.paintComponent(page);
        drawCircle(50,50,20);
    }

    private void drawCircle(int x, int y, int radius)
    {
        drawOval(x - radius, y - radius, radius*2, radius*2);
    }
}

Upvotes: 0

Views: 38118

Answers (2)

Dreamspace President
Dreamspace President

Reputation: 1118

import java.awt.Shape;
import java.awt.geom.Ellipse2D;

public static Shape getCircle(
                        final double x,
                        final double y,
                        final double r
                             ) {

    return new Ellipse2D.Double(x - r, y - r, r * 2, r * 2);
}

Advantages:

  • You don't have to pass or get the Graphics context.
  • You can choose whether to draw or fill the circle without changing the Method (e.g. do g.draw(getCircle(x, y, r)); or g.fill... in your paint() Method).
  • You use AWT draw Method syntax to actually draw/fill the circle.
  • You get a circle in double precision coordinates.

You said that "The drawCircle method needs to call drawOval.", but maybe you were just not aware of the alternative.

Upvotes: 0

S73417H
S73417H

Reputation: 2671

You can get the graphics context by calling getGraphics() on a swing component. But i would still create my drawing methods to accept the graphics context.

For instance

private void drawCircle(Graphics g, int x, int y, int radius) {
   g.fillOval(x-radius, y-radius, radius*2, radius*2)
}

Alternatively,

private void drawCircle(int x, int y, int radius) {
  getGraphics().fillOval(x-radius, y-radius, radius*2, radius*2)
}

Be aware of the fact that getGraphics() can return null however. You are much better off calling your drawCircle() method from within the paint() method and passing it the Graphics context.

E.g.

public void paint(Graphics g) {
  super.paint(g);
  drawCircle(g, 10, 10, 5, 5);
}

Upvotes: 3

Related Questions