简体   繁体   中英

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?

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.

In Processing 3.x PApplet no longer extends Applet:

Applet is gone — Java's java.awt.Applet is no longer the base class used by PApplet, so any sketches that make use of Applet-specific methods (or assume that a PApplet is a Java AWT Component object) will need to be rewritten.

from github repo wiki page Changes in 3.0

If you need the applet functionality, use an older version (2.2.1 or prior).

The following is a template for Processing 3.x programs in Eclipse. However, you should run these as 'Java Application', rather than 'Java Applet':

import processing.core.PApplet;

public class P5Template extends PApplet {

    public void settings() {

        size(512, 200);
    }

    public void setup() {

    }

    public void draw() {

        background(0, 30, 0);
    }

    public static void main(String[] args) {

        PApplet.main(new String[] { P5Template.class.getName() });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM