"Exception in thread "Animation Thread" error when using Processing in Eclipse - java

I have a created a very simple processing sketch in eclipse with classes.Eclipse says the code contains no errors, only warnings, however it fails at runtime and the console displays the following errors:
Exception in thread "Animation Thread" java.lang.NullPointerException
at processing.core.PApplet.ellipse(PApplet.java:12174)
at assignment.Tracking.display(Tracking.java:15)
at assignment.Assignment.draw(Assignment.java:16)
at processing.core.PApplet.handleDraw(PApplet.java:2386)
at processing.core.PGraphicsJava2D.requestDraw(PGraphicsJava2D.java:240)
at processing.core.PApplet.run(PApplet.java:2256)
at java.lang.Thread.run(Unknown Source)
The code is the following:
package assignment;
import processing.core.*;
public class Assignment extends PApplet {
Tracking tracking;
public void setup() {
size(500, 500);
tracking = new Tracking();
}
public void draw() {
tracking.display();
}
}
And the code for the Tracking class is:
package assignment;
import processing.core.*;
public class Tracking extends PApplet
{
int test;
public Tracking() {
test = 100;
}
void display(){
ellipse(test, test, test, test);
}
}
I believe I have imported the necessary processing .jar files. Thanks in advance for any help

It looks like the problem is that you do the setup in the Assignment class, but calls ellipse() from the Tracking class. Note that Assignment and Tracking are two different PApplets. You call size(500, 500) in Assignment, but Tracking has no defined size.

Related

IllegalStateException due to thread issue

I'm trying to create a window for an application. The size of the window is determined by getting the bounds of the primary screen. In order to do this I have created two classes.
RealMain class is the actual class that does everything:
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Rectangle2D;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.stage.Screen;
import javafx.stage.Stage;
public class RealMain extends Application {
public static final double minWindowWidth;
public static final double minWindowHeight;
//Get primary screen bounds
static {
System.out.println(Thread.currentThread().getName());
Rectangle2D screenBounds = Screen.getPrimary().getBounds();
minWindowWidth = screenBounds.getWidth() / 2;
minWindowHeight = screenBounds.getHeight() / 1.5;
}
#Override
public void start(Stage primaryStage) throws Exception{
Scene scene = new Scene(new HBox(), minWindowWidth, minWindowHeight);
primaryStage.setScene(scene);
primaryStage.sizeToScene();
primaryStage.show();
primaryStage.setMinWidth(primaryStage.getWidth());
primaryStage.setMinHeight(primaryStage.getHeight());
}
public static void main(String[] args) {
launch(args);
}
}
Main class is just an entry point into the program. All it does is call the main method of RealMain. Why do I need to use the Main class in the first place (why not just run the main method of RealMain)? It's because of a different problem I had, where I would get "Error: JavaFX runtime components are missing, and are required to run this application." when running the program as a jar on macOS. Apparently setting a regular java class as an entry point will fix this (one place where I found this solution is here), hence I needed to create the Main class.
public class Main {
public static void main(String[] args) {
RealMain.main(args);
}
}
It works fine when I run the main method of the RealMain class. However, if I use the main method of the Main class, I get the following error:
Exception in thread "main" java.lang.ExceptionInInitializerError
at RealMain.<clinit>(RealMain.java:19)
at Main.main(Main.java:4)
Caused by: java.lang.IllegalStateException: This operation is permitted on the event thread only; currentThread = main
at com.sun.glass.ui.Application.checkEventThread(Application.java:441)
at com.sun.glass.ui.Screen.setEventHandler(Screen.java:369)
at com.sun.javafx.tk.quantum.QuantumToolkit.setScreenConfigurationListener(QuantumToolkit.java:684)
at javafx.stage.Screen.<clinit>(Screen.java:74)
... 2 more
So it seems when running the program from Main class, the main thread is used to execute the static block, which seems to be what causes the error (as to why, I have no idea). Meanwhile when running the program from RealMain class, the JavaFX Application Thread is used for the static block, which works fine. I guess the logical solution would be to somehow force the program to change threads and execute the static block on the JavaFX Application Thread, but I have no idea how to do that.
Could anyone please help me figure this out?

Extracting draw() method on a separate loop (PApplet as a JADE Agent)

I am creating a JADE-based agent system on Java, and I want to use Processing for visualizing these agents. Now the JADE framework runs on it's own, and a Processing PApplet is instantiated as one of the agents, which is a singleton.
Every time one of the (other types of) agents change, they call the redraw() method of the PApplet. The problem is, the PApplet doesn't call it's draw() method, since it's not running on it's own thread.
How do I fix this?
EDIT:
public class Manager extends Agent{
//The Agent object that runs as a separate thread under JADE framework.
protected void setup(){
...
javax.swing.SwingUtilities.invokeLater(new VisualizerThreadRunnable(this));
...
}
}
class VisualizerThreadRunnable implements Runnable {
public VisualizerThreadRunnable(Manager m){
...
}
public void run(){
System.out.println("visualizer being launched...");
Visualizer visualizer = new Visualizer(manager);
visualizer.setVisible(true);
}
}
public class Visualizer extends PApplet {
//from examples on http://processing.org/tutorials/eclipse/
public Visualizer(Manager m){
this.m = m;
...
}
public void setup() {
size(200,200);
background(0);
}
public void draw() {
stroke(255);
if (mousePressed) {
line(mouseX,mouseY,pmouseX,pmouseY);
}
}
}
In the visualizer thread you also need to initialize the PApplet using init():
public void run(){
System.out.println("visualizer being launched...");
Visualizer visualizer = new Visualizer(manager);
visualizer.init();//This is pretty important
visualizer.setVisible(true);
}
For more information checkout PApplet's javadocs.
This should solve the Processing side of the problem. I've never used Jade before,
so I don't know if the thread will stay on. Do check if that happens, if not maybe you should keep that thread running.

Using ControlP5 with processing in eclipse results in IllegalArgumentException on keypress

I have a Processing project making use of the ControlP5 library running within eclipse in which, upon any keypress on the keyboard, crashes with an IllegalArgumentException:
Exception in thread "Animation Thread" java.lang.IllegalArgumentException: argument type mismatch
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at processing.core.PApplet$RegisteredMethods.handle(PApplet.java:1076)
at processing.core.PApplet.handleKeyEvent(PApplet.java:2848)
at processing.core.PApplet.dequeueKeyEvents(PApplet.java:2793)
at processing.core.PApplet.handleDraw(PApplet.java:2132)
at processing.core.PGraphicsJava2D.requestDraw(PGraphicsJava2D.java:197)
at processing.core.PApplet.run(PApplet.java:1998)
at java.lang.Thread.run(Unknown Source)
The program (running in an applet) runs perfectly fine with mouse dragging, sliders, etc, until a key is pressed. It seems like there is some sort of unknown keylistener waiting for input and using it incorrectly? It is difficult to tell because the exception refers to java code which is unrelated to the processing code which I wrote.
Even if I have a program which only defines a ControlP5 object, the program encounters the same error:
import processing.core.*;
import controlP5.*;
public class Lensing extends PApplet {
ControlP5 controlP5;
public Lensing() {
}
public void setup() {
controlP5 = new ControlP5(this);
}
public void draw() {
}
public static void main(String args[]) {
PApplet.main(new String[] { "--present", "edu.umd.astro.Lensing" });
}
}
Comment out the single controlP5 definition, and no exception occurs.
Turns out it was an issue related to using the 2.0b1 core jar file, and can be remedied by updating to 2.0b3 from http://processing.org/download/
credit to reply on here https://forum.processing.org/topic/using-controlp5-with-processing-in-eclipse-results-in-illegalargumentexception-on-keypress

URLClassLoader, "hot-swapping" jar files and ClassFormatError - weird behavior

Rewritten from scratch # Friday, 25 May, about 16:00 GMT
(Code is cleaner now, bug can be reproduced and the question is more clear)
Original problem: I'm writing a server app that's required to accept files from clients over the net and process them with certain classes, which are loaded from locally stored .jar-files via URLClassLoader. Almost everything works correctly, but those jar-files are hot-swapped (without restarting the server app) from time to time to apply hotfixes, and if we're unlucky enough to update .jar-file at the same time class from it is being loaded, ClassFormatError is thrown, with remarks about "truncated class" or "excess bytes at the end". That's to be expected, but the whole application becomes unstable and starts to behave weird after that - those ClassFormatError exceptions keep happening when we try to load the class again from the same jar that was updated, even though we use new instance of URLClassLoader and it happens in different app thread.
The app is running and compiled on Debian Squeeze 6.0.3/Java 1.4.2, migration is not within my power.
Here's a simple code that mimics app behavior and roughly describes the problem:
1) Classes for main app and per-client threads:
package BugTest;
public class BugTest
{
//This is a stub of "client" class, which is created upon every connection in real app
public static class clientThread extends Thread
{
private JarLoader j = null;
public void run()
{
try
{
j = new JarLoader("1.jar","SamplePlugin.MyMyPlugin","SampleFileName");
j.start();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
//Main server thread; for test purposes we'll simply spawn new clients twice a second.
public static void main(String[] args)
{
BugTest bugTest = new BugTest();
long counter = 0;
while(counter < 500)
{
clientThread My = null;
try
{
System.out.print(counter+") "); counter++;
My = new clientThread();
My.start();
Thread.currentThread().sleep(500);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
2) JarLoader - a wrapper for loading classes from .jar, extends Thread. Here we load a class which implements a certain interface a:
package BugTest;
import JarPlugin.IJarPlugin;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
public class JarLoader extends Thread
{
private String jarDirectory = "jar/";
private IJarPlugin Jar;
private String incomingFile = null;
public JarLoader(String JarFile, String JarClass, String File)
throws FileNotFoundException, MalformedURLException, ClassNotFoundException, InstantiationException, IllegalAccessException
{
File myjarfile = new File(jarDirectory);
myjarfile=new File(myjarfile,JarFile);
if (!myjarfile.exists())
throw new FileNotFoundException("Jar File Not Found!");
URLClassLoader ucl = new URLClassLoader(new URL[]{myjarfile.toURL()});
Class JarLoadedClass =ucl.loadClass(JarClass);
// ^^ The aforementioned ClassFormatError happens at that line ^^
Jar = (IJarPlugin) JarLoadedClass.newInstance();
this.setDaemon(false);
incomingFile = File
}
public void run()
{
Jar.SetLogFile("log-plug.txt");
Jar.StartPlugin("123",incomingFile);
}
}
3) IJarPlugin - a simple interface for pluggable .jars:
package JarPlugin;
public interface IJarPlugin
{
public void StartPlugin(String Id, String File);
public void SetLogFile(String LogFile);
}
4) the actual plugin(s):
package SamplePlugin;
import JarPlugin.IJarPlugin;
public class MyMyPlugin implements IJarPlugin
{
public void SetLogFile(String File)
{
System.out.print("This is the first plugin: ");
}
public void StartPlugin(String Id, String File)
{
System.out.println("SUCCESS!!! Id: "+Id+",File: "+File);
}
}
To reproduce the bug, we need to compile a few different .jars using same class name, whose only difference is number in "This is the Nth plugin: ". Then start the main application, and then rapidly replace the loaded plugin file named "1.jar" with other .jars, and back, mimicing the hotswap. Again, ClassFormatError is to be expected at some point, but it keeps happening even when the jar is completely copied (and is NOT corrupt in any way), effectively killing any client threads which try to load that file; the only way to get out from this cycle is to replace the plugin with another one. Seems really weird.
The actual cause:
It all became sort of clear once I simplified my code even more and got rid of clientThread class, simply instancing and starting the JarLoader inside the while loop in main. When ClassFormatError was thrown, it not just printed the stack trace out, but actually crashed the whole JVM (exit with code 1). The reason is not as obvious as it seems now (it wasn't for me, at least): ClassFormatError extends Error, not Exception. Hence it passes through catch(Exception E) and the JVM exits because of uncaught exception/error, BUT since I spawned thread which caused error from another spawned (client) thread, only that thread crashed. I guess it's because of the way Linux handles Java threads, but I'm not sure.
The (makeshift) solution:
Once uncaught error cause became clear, I tried to catch it inside the "clientThread". It sort of worked (I removed the stacktrace printout and printed my own message), but the main problem was still present: the ClassFormatError, even though caught properly, kept happening until I replace or remove the .jar in question. So I took a wild guess that some sort of caching might be a culprit, and forced URLClassLoader reference invalidation and Garbage Collection by adding this to clientThread try block:
catch(Error e)
{
System.out.println("Aw, an error happened.");
j=null;
System.gc();
}
Surprisingly, it seems to work! Now error only happens once, and then file class just loads normally, as it should. But since I just made an assumption, but not understood a real cause, I'm still worried - it works now, but there's no guarantee that it will work later, inside a much more complicated code.
So, could anyone with deeper understanding of Java enlighten me on what's the real cause, or at least try to give a direction? Maybe it's some known bug, or even expected behavior, but it's already way too complicated for me to understand on my own - I'm still a novice. And can I really rely on forcing GC?

nullPointerException in a MIDLet

I have written the following Java Application:
import java.util.Timer;
import java.util.TimerTask;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.midlet.MIDlet;
public class JavaApplication6 extends MIDlet
{
private static Form clockForm=null;
private static StringItem clockItem=new StringItem("hello", "World!");
private static ClockTask task=null;
private static Timer timer=null;
static class ClockTask extends TimerTask
{
private int count=0;
#Override
public void run()
{
count++;
clockItem.setText("hello "+count);
}
}
public static void JavaApplication6() throws Exception
{
clockForm=new Form("Clock");
clockItem=new StringItem("","0");
clockForm.append(clockItem);
}
#Override
public void startApp()
{
task=new ClockTask();
timer=new Timer();
timer.schedule(task,1000,1000);
Display.getDisplay(this).setCurrent(clockForm);}
#Override
public void pauseApp()
{}
public void destroyApp(boolean unconditional)
{}
public static void main(String[] args) {
JavaApplication6 test=new JavaApplication6();
test.startApp();
}
}
but when I run it, it gives me the following exception on the last line of startApp();
Exception in thread "main" java.lang.NullPointerException
at javax.microedition.lcdui.Display.<init>(Display.java:420)
at javax.microedition.lcdui.Display.getDisplay(Display.java:447)
at javaapplication6.JavaApplication6.startApp(JavaApplication6.java:42)
at javaapplication6.JavaApplication6.main(JavaApplication6.java:56)
You created static method JavaApplication6 named as it is the constructor. But it is not. So it is not called when you say JavaApplication6 test=new JavaApplication6();. Therefore clockForm remains uninitialized, i.e. null. So, line
Display.getDisplay(this).setCurrent(clockForm);
throws NPE becuase clockForm is null at this point.
The solution is to remove static void from line public static void JavaApplication6() throws Exception. It should look like
public JavaApplication6() throws Exception
In this case it becomes constructor and everything will work.
Good luck.
You seem to be approaching things in a fundamentally wrong way.
I mean, even if you somehow manage to figure and hack through all of the null pointer exceptions, you will not get a valid MIDlet application code.
Thing is, because class JavaApplication6 extends MIDlet, the following line will throw runtime exception at any properly functioning MIDP implementation (read: at any correctly working device):
JavaApplication6 test=new JavaApplication6(); // SecurityException in runtime
This is the way how things are specified by MIDP (JSR 118) API. Above line means that application attempts to invoke MIDlet constructor bypassing the AMS, which will cause SecurityException in runtime.
This is clearly explained in MIDlet constructor javadocs, note what is stated in Throws:
protected MIDlet()
Protected constructor for subclasses. The application management software
is responsible for creating MIDlets and creation of MIDlets is restricted.
MIDlets should not attempt to create other MIDlets.
Throws:
SecurityException - unless the application management software is creating
the MIDlet.

Categories