Roger
Roger

Reputation: 3256

Java - Calling a paintComponent Method

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);
}}

Upvotes: 0

Views: 438

Answers (1)

Sourabh Bhat
Sourabh Bhat

Reputation: 1893

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.

Upvotes: 1

Related Questions