Question

I would like to have a circle that can be recreated by calling its method with the given x,y,color parameters. But i'm having difficulty in doing so. I want to use JComponent as an object rather than a component.

public class OlympicRingsComponent extends JComponent {

public void paintComponent(Graphics g) {

    super.paintComponent(g);

    Graphics2D g2 = (Graphics2D)g;
    g2.translate(10, 10);
    g2.setStroke(new BasicStroke(7));

    Ellipse2D.Double circle = new Ellipse2D.Double(0,0,100,100);

    g2.setPaint(Color.BLUE);
    g2.draw(circle);

}}

this code works fine. But i would like to be able to call a method in order to create a new ellipse.

public class OlympicRingsComponent extends JComponent {

protected void paintComponent(Graphics g) {

    super.paintComponent(g);

    Graphics2D g2 = (Graphics2D)g;
    g2.translate(10, 10);
    g2.setStroke(new BasicStroke(7));

    ring(10 , 20 , "Blue");

}
public void ring(int x , int y , String color) {
    Ellipse2D.Double circle = new Ellipse2D.Double( x , y ,100,100);

    g2.setPaint(Color.getColor(color));
    g2.draw(circle);
}}
Was it helpful?

Solution

Need to add graphics2D argument to ring() method like this:

public void ring(int x , int y , String color, graphics2D g2) {
    Ellipse2D.Double circle = new Ellipse2D.Double( x , y ,100,100);

    g2.setPaint(Color.getColor(color));
    g2.draw(circle);
}

and call ring() with the graphics2D argument:

ring(10 , 20 , "Blue", g2);

I think that should work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top