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);
}
}
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
Alternatively,
Be aware of the fact that
getGraphics()can returnnullhowever. You are much better off calling your drawCircle() method from within the paint() method and passing it the Graphics context.E.g.