Search code examples
javaeclipseappletprocessing

Java error: cannot cast to java.applet.Applet in Eclipse


So here is really simple code that will not compile in Eclipse:

import processing.core.*;

public class MyPApplet extends PApplet {
}

I'm trying to run it as a Java Applet, but I get the error:

java.lang.ClassCastException: MyPApplet cannot be cast to java.applet.Applet

The problem is PApplet is a class from processing package, and it extends java.applet.Applet, and MyPApplet extends PApplet, but I still get this error. It makes no sense. Why can't MyPApplet be cast to java.applet.Applet?

Can someone please help?


Solution

  • Like George said, PApplet no longer extends Applet as of Processing 3.

    But instead of going back to an old version of Processing, I would recommend using the runSketch() function to run your sketch:

    public class MyPapplet extends PApplet {
    
      public static void main(String... args){
        String[] pArgs = {"MyPapplet "};
        MyPapplet mp = new MyPapplet ();
        PApplet.runSketch(pArgs, mp);
      }
    
      public void settings() {
        size(200, 100);
      }
      public void draw() {
        background(255);
        fill(0);
        ellipse(100, 50, 10, 10);
      }
    }
    

    If you really need access to the underlying native component, you have to write code that depends on what renderer you're using. Here's how you'd do it with the default renderer:

    PSurfaceAWT awtSurface = (PSurfaceAWT)mp.surface;
    PSurfaceAWT.SmoothCanvas smoothCanvas = (PSurfaceAWT.SmoothCanvas)awtSurface.getNative();
    

    But the first approach should be good enough for most people, so try that first.