tags:

views:

33

answers:

1

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);
    }
}
+1  A: 

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);
}
S73417H
True, but this is a homework question. If this can't be done without Graphics, then I'll just tell my professor.
Raptrex
Thanks, getGraphics() worked
Raptrex
Ya, im guessing its returning null when I'm testing it on Windows, however, it works on OSX.
Raptrex