Search code examples
javaswingpaintcomponentgraphics2d

Using chained methods with Graphics2D


public class FaceComponent extends JComponent
{  
   public void paintComponent(Graphics g)
   {  
      Graphics2D g2 = (Graphics2D) g;
      Ellipse2D.Double head = new Ellipse2D.Double(5, 10, 100, 150);
      Rectangle eye = new Rectangle(25, 70, 15, 15);
      Line2D.Double mouth = new Line2D.Double(30, 110, 80, 110);
      g2.setColor(Color.GREEN)
        .fill(eye)
        .eye.translate(50, 0);
        .fill(eye)
        .setColor(Color.RED)
        .draw(mouth)
        .setColor(Color.BLUE)
        .drawString("Hello, World!", 5, 175);
   }
}

Is there a reason chaining the methods on object g2 causes error "cannot invoke (method) on primitive type void, which I may be overlooking?


Solution

  • The methods setColor, fill, etc. have void return types so can't be chained like this, rather they need to be invoked separately

    g2.setColor(Color.GREEN);
    g2.fill(eye);
    ...