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
Related
I'm working on an app, that searches some files in the directed folder and prints them in TableView<myFile> foundFilesList, that is stored in the Main class. myFile just extends File a bit. The searching is done using service in background thread, that puts found data to ObservableList<myFile> filesOfUser.
I want to display current amount of find files in TextField foundFilesAmount in the same view, where TableView with files is located -- ResultsView
To do that, I added a ListChangeListener for foundFilesList to ResultsView controller, that uses method setText to print current size of filesOfUser. It looks like:
Main.filesOfUser.addListener(new ListChangeListener<myFile>() {
#Override
public void onChanged(Change<? extends myFile> c) {
while (c.next()){
if (c.wasAdded())
setCounter(c.getAddedSize());
}
}
});
void setCounter (int number) contains only
int currValue = Integer.valueOf(foundFilesAmount.getText());
foundFilesAmount.setText(String.valueOf(currValue + number));
And now what the problem is. Textfield with current amount of find files is updated very fast, and from one moment it stops doing it. In the console I see lots of repeated NullPointerException's from JavaFX Application Thread. Its' contents:
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
at com.sun.javafx.text.PrismTextLayout.getRuns(PrismTextLayout.java:236)
at javafx.scene.text.Text.getRuns(Text.java:317)
at javafx.scene.text.Text.updatePGText(Text.java:1465)
at javafx.scene.text.Text.impl_updatePeer(Text.java:1500)
at javafx.scene.Node.impl_syncPeer(Node.java:503)
at javafx.scene.Scene$ScenePulseListener.synchronizeSceneNodes(Scene.java:2290)
at javafx.scene.Scene$ScenePulseListener.pulse(Scene.java:2419)
at com.sun.javafx.tk.Toolkit.lambda$runPulse$30(Toolkit.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.Toolkit.runPulse(Toolkit.java:354)
at com.sun.javafx.tk.Toolkit.firePulse(Toolkit.java:381)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:510)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:490)
at com.sun.javafx.tk.quantum.QuantumToolkit.lambda$runToolkit$404(QuantumToolkit.java:319)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Thread.java:745)
I tried to set sort of delay before using setText, like updating value in foundFilesAmount only after 5'th, 10'th, 15'th update, etc. But if the search works longer, exceptions are still thrown.
Is there a correct method to show current amount of found files, that contains real amount and doesn't cause so much exceptions?
Thanks in advance.
The correct way is not doing the updates of the UI on a thread other than the application thread. This can otherwise lead to issues with rendering/layouting.
You could use a Task to do the updates to the updates however:
Task<ObservableList<myFile>> task = new Task<
Task<ObservableList<myFile>>() {
#Override
protected ObservableList<myFile> call() throws Exception {
ObservableList<myFile> files = FXCollections.observableArrayList();
while (...) {
...
files.add(...);
updateMessage(Integer.toString(files.size()));
...
}
return files;
}
};
task.setOnSucceeded(evt -> tableView.setItems(task.getValue()));
Thread t = new Thread(task);
textField.textProperty().bind(task.messageProperty());
t.setDaemon(true);
t.start();
try something like this:
Platform.runLater(new Runnable() {
#Override
public void run() {
// update your JavaFX controls here
}
});
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.
I have been working on this game for a while now, which actually has different game modes built into it. At first, I have been handling the execution by just exiting the program after the user has lost, or wants to exit. Since not only is it annoying to have to re-open the program, and when users don't understand why it closed, I have a reason to after losing or wanting to exit, that they return to the main menu.
The problem that appears at this time is that I am using swing in the main part of my design of the game. This not only includes the main menu, but other menus, and even in part with the game. Swing is being used is for the interactivity of buttons and other primary features. So now that I am switching to returning to the main menu and everything, I have been having to rewrite basically the whole base of rendering and switching between the windows.
Since I am rewriting the render method of the game, I decided to make a StateRenderer class. From this, it would handle and decide if it currently even needs to process. So within the run() method, I put a line of code that checks if it even needs to render at a state of a menu.
#Override
public void run() {
long lastTime = System.nanoTime();
long timer = System.currentTimeMillis();
final double ns = BILLION / UPDATE_RATE;
double delta = 0;
int updates = 0, frames = 0;
while (running) {
// right here I am checking the state for it
GameState state = CellDefender.getGameState();
if (state == GameState.MAIN_MENU || state == GameState.STORE_MENU || state == GameState.SETTINGS_MENU) continue;
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while (delta >= 1) {
update();
updates++;
delta--;
}
render();
frames++;
if (System.currentTimeMillis() - timer >= 1000) {
while (System.currentTimeMillis() - timer >= 1000) // while idling it builds up much, and makes it less annoying when debugging
timer += 1000;
System.out.println("UPS: " + updates + ", FPS: " + frames);
updates = 0;
frames = 0;
}
}
stop();
}
Now, that works fine when I decide to switch from the main menu to an actual game mode, but if I were to lose on the mode, or want to exit to main, I get this nasty error, which I have no idea how I would ever fix it:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: component argument pData
at sun.java2d.windows.GDIWindowSurfaceData.initOps(Native Method)
at sun.java2d.windows.GDIWindowSurfaceData.<init>(Unknown Source)
at sun.java2d.windows.GDIWindowSurfaceData.createData(Unknown Source)
at sun.java2d.d3d.D3DScreenUpdateManager.getGdiSurface(Unknown Source)
at sun.java2d.d3d.D3DScreenUpdateManager.createGraphics(Unknown Source)
at sun.awt.windows.WComponentPeer.getGraphics(Unknown Source)
at java.awt.Component.getGraphics(Unknown Source)
at sun.awt.RepaintArea.paint(Unknown Source)
at sun.awt.windows.WComponentPeer.handleEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
The only part that I understand is I'm doing something completely wrong with AWT, which deals with things such as Graphics and Canvas. It would probably be a horrible idea to just engulf the error with a try..catch method, but then again I don't really know where it is caused.
To get into details about how I switch, here is from my main menu to an actual GameMode:
private void initListeners() {
btnRegular.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setGameState(GameState.REGULAR);
renderer.switchDisplay(RegularMode.class);
}
});
// more code is here, but useless for now
}
My renderer is my StateRenderer which is meant to be built to handle all rendering for the game, when you are actually on a screen that has the Canvas element, and is tracked by the GameState. Now I will show you what is thrown into the renderer.switchDisplay(Class class) method.
public void switchDisplay(Class<? extends GameMode> mode) {
if (mode == RegularMode.class) {
currentMode = new RegularMode(size);
setPreferredSize(size);
screen = new Screen(size.width, size.height);
panel.add(currentMode.getFunctionBar(), BorderLayout.NORTH);
panel.add(currentMode.getScoreBar(), BorderLayout.SOUTH);
// -- extra stuff that is similar --
} else return;
JFrame frame = CellDefender.getFrame();
frame.remove(CellDefender.getMainPanel());
panel.add(this, BorderLayout.CENTER);
frame.add(panel);
frame.validate();
frame.repaint();
frame.pack();
currentMode.initialize();
requestFocus();
}
This may be somewhat inefficient, but all of this seems to work seemingly fine. Now to dive into when everything is getting switched back to the main menu that throws all of the errors!
This is the code that is ran that is directly causing the error:
public static void switchDisplay() {
setGameState(GameState.MAIN_MENU); // Switched the game state, should stop looping.
frame.setContentPane(panel);
frame.validate();
frame.repaint();
frame.pack();
}
This, of course, gives me a complete feeling that the error lies somewhere in my StateRenderer class, and more specifically anything that relates into the run() method. The part that I have already handled the loop about the rendering.
Summary
So I am having a problem when switching from a panel with a Canvas component, that implements Runnable. In my code, I have handled the problem about it rendering when it doesn't have a visible Canvas, or when the GameState is not one that is for the game to render. However, when switching from a canvas that is currently being rendered and updated to a menu that isn't doing so causes a NullPointerException.
I would like to go ahead and thank anyone and everyone for your help, because this issue really has me stumped.
Edit(s)
With further testing that I always decide to do when I ask for help, I see the problem occurs in the CellDefender.switchDisplay() method at the line frame.validate(). I don't understand why this is causing the problem.
According to the discussion in the comments, the problem is most likely related to a violation of the Swing "Single Thread Rule":
Once a Swing component has been realized, all code that might affect or depend on the state of that component should be executed in the event-dispatching thread.
The results of violating this rule may be arbitrarily odd, but NullPointerExceptions from deeply inside the Swing management infrastructure are among the more common ones.
In many cases, this issue can be resolved by a pragmatic pattern: Assume you have a method that modifies Swing components:
void modifySwingComponents()
{
someComponent.add(someOtherComponent);
someComponent.remove(somethingElse);
someTextComponent.setText("Text");
...
}
Then you can easily check whether the Single Thread Rule is violated by inserting something like
System.out.println(Thread.currentThread());
in this method. It should always print Thread[AWT-EventQueue-0,6,main] (or similar, indicating that the method is executed on the Event Dispatch Thread). Alternatively, you can directly query
System.out.println(SwingUtilities.isEventDispatchThread());
If the method is called from a Thread that is not the Event Dispatch Thread (EDT), you may "wrap" this method into a Runnable that you put on the event queue:
void modifySwingComponents()
{
if (SwingUtilities.isEventDispatchThread())
{
// We're on the right thread - direcly call the method
modifySwingComponentsOnEDT();
}
else
{
// Put the task to execute the method in the event queue,
// so that it will be executed on the EDT as soon as possible
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
modifySwingComponentsOnEDT();
}
});
}
}
// Always called on the EDT!
void modifySwingComponentsOnEDT()
{
someComponent.add(someOtherComponent);
someComponent.remove(somethingElse);
someTextComponent.setText("Text");
...
}
But NOTE that although this looks simple and may seem to easily resolve certain issues, it does NOT release you from the duty to diligently check and document which method is executed on which thread.
Can anyone please tell me why I get the following exceptions
Exception in thread "main" java.lang.IllegalArgumentException adding a window to a container :
java.awt.Container.checkNotAWindow(Unknown Source)
java.awt.Container.addImpl(Unknown Source)
java.awt.Container.add(Unknown Source)
javax.swing.JFrame.addImpl(Unknown Source)
java.awt.Container.add(Unknown Source)
clockframe.<init>(clockframe.java:14)
clockframe.main(clockframe.java:32)
My code which is inside clockpanel.java file is below: I am beginner so I don't know how to work this out......
import java.awt.*;
import javax.swing.*;
public class clockframe extends JFrame
{
public clockframe()
{
super("Clock");
setLookAndFeel();
setSize(225, 125);
FlowLayout flo = new FlowLayout();
setLayout(flo);
clockpanel time = new clockpanel();
add(time);
setVisible(true);
}
private void setLookAndFeel()
{
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
}
catch (Exception exc)
{
// ignore error
}
}
public static void main(String args[])
{
clockframe clock = new clockframe();
}
}
Take a look at the JFrame documentation
IllegalArgumentException - if index is invalid
IllegalArgumentException - if adding the container's parent to itself
IllegalArgumentException - if adding a window to a container
It is looking likely that clockpanel inherits from Window thus triggering the last clause.
Edit: no need to guess any more.. just noticed the top of your stack trace.. this is the cause.
clockpanel probably extends a window such as JFrame. You probably meant to extend JPanel instead (although doing so is not necessary unless adding new functionality such as custom painting to the new JPanel).
Answer lies it self in stack trace :
thread "main" java.lang.IllegalArgumentException adding a window to a container
You are adding window to container, which is not allowed.
We are building an application based on the Netbeans Platform, and one part of it is an editor for a specific language we use.
We have the following class to highlight errors in the syntax:
class SyntaxErrorsHighlightingTask extends org.netbeans.modules.parsing.spi.ParserResultTask {
public SyntaxErrorsHighlightingTask () {
}
#Override
public void run (org.netbeans.modules.parsing.spi.Parser.Result result, org.netbeans.modules.parsing.spi.SchedulerEvent event) {
try {
final javax.swing.text.Document document = result.getSnapshot().getSource ().getDocument(false);
final List<ErrorDescription> errors = new ArrayList<ErrorDescription> ();
// finds errors on the document and add them to 'errors' list
}
/***
OFFENDING CODE GOES HERE
***/
} catch (javax.swing.text.BadLocationException ex1) {
org.openide.util.Exceptions.printStackTrace (ex1);
} catch (org.netbeans.modules.parsing.spi.ParseException ex1) {
Exceptions.printStackTrace (ex1);
}
}
#Override
public int getPriority () {
return 100;
}
#Override
public Class<? extends Scheduler> getSchedulerClass () {
return Scheduler.EDITOR_SENSITIVE_TASK_SCHEDULER;
}
#Override
public void cancel () {
}
}
The offending code, that throws an exception, is this:
org.netbeans.spi.editor.hints.HintsController.setErrors (document, "testsequence", errors);
Based on searching results, it was changed to the following:
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
System.err.println("is EDT? " + SwingUtilities.isEventDispatchThread());
HintsController.setErrors (document, "testsequence", errors);
}
});
The following is what happens when a syntax error is introduced in the editor:
is EDT? true
SEVERE [org.openide.util.RequestProcessor]: Error in RequestProcessor org.netbeans.spi.editor.hints.HintsController$1
java.lang.IllegalStateException: Must be run in EQ
at org.netbeans.editor.Annotations.addAnnotation(Annotations.java:195)
at org.netbeans.modules.editor.NbEditorDocument.addAnnotation(NbEditorDocument.java:251)
at org.openide.text.NbDocument.addAnnotation(NbDocument.java:504)
at org.netbeans.modules.editor.hints.AnnotationHolder$NbDocumentAttacher.attachAnnotation(AnnotationHolder.java:235)
at org.netbeans.modules.editor.hints.AnnotationHolder.attachAnnotation(AnnotationHolder.java:208)
at org.netbeans.modules.editor.hints.AnnotationHolder.updateAnnotationOnLine(AnnotationHolder.java:674)
at org.netbeans.modules.editor.hints.AnnotationHolder.setErrorDescriptionsImpl(AnnotationHolder.java:899)
at org.netbeans.modules.editor.hints.AnnotationHolder.access$1300(AnnotationHolder.java:113)
at org.netbeans.modules.editor.hints.AnnotationHolder$4.run(AnnotationHolder.java:812)
at org.netbeans.editor.BaseDocument.render(BaseDocument.java:1409)
at org.netbeans.modules.editor.hints.AnnotationHolder.setErrorDescriptions(AnnotationHolder.java:809)
at org.netbeans.modules.editor.hints.HintsControllerImpl.setErrorsImpl(HintsControllerImpl.java:111)
at org.netbeans.modules.editor.hints.HintsControllerImpl.setErrors(HintsControllerImpl.java:93)
at org.netbeans.spi.editor.hints.HintsController$1.run(HintsController.java:79)
at org.openide.util.RequestProcessor$Task.run(RequestProcessor.java:1424)
at org.openide.util.RequestProcessor$Processor.run(RequestProcessor.java:1968)
Caused: org.openide.util.RequestProcessor$SlowItem: task failed due to
at org.openide.util.RequestProcessor.post(RequestProcessor.java:425)
at org.netbeans.spi.editor.hints.HintsController.setErrors(HintsController.java:77)
at com.#.#.#.editor.parser.SyntaxErrorsHighlightingTask$1.run(SyntaxErrorsHighlightingTask.java:74)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:641)
at java.awt.EventQueue.access$000(EventQueue.java:84)
at java.awt.EventQueue$1.run(EventQueue.java:602)
at java.awt.EventQueue$1.run(EventQueue.java:600)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:611)
at org.netbeans.core.TimableEventQueue.dispatchEvent(TimableEventQueue.java:148)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
[catch] at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
What happens is, the call is to HintsController is being made in the EDT (EventDispatch Thread). However, Annotations.addAnnotation() is being run in another thread - sometimes in the "System clipboard synchronizer" thread, sometimes in the "Inactive RequestProcessor" thread. Since it checks if its being run on the EDT, it always throws an IllegalStateException.
I'm no expert in using the Netbeans Platform, and I'm pretty new to this specific application on the company - so I might be missing something really obvious. Google didn't help much. Anyone has any advice?
Turns out, it was not a problem with the code after all.
As pointed on the NetBeans-dev list:
HintsController.setErrors can be called from any thread - it uses its
own worker thread, and reschedules to AWT thread when necessary.
The requirement to invoke Annotations.addAnnotation in AWT thread has
been removed quite some time ago by:
http://hg.netbeans.org/main-silver/rev/db82e4e0fbcc
The same changeset also removed automatic rescheduling into AWT thread
in NbDocument.addAnnotation. So it seems that the build you are using
has the second part of the changeset, but not the first part (...)
After a careful review of maven's pom.xml files, I realized that the application was loading newer versions of the libs while the module was loading older versions, so it would run the wrong code. Related SO question about that here.
Maybe you should try to update your errors with a method like this one :
private void updateError(javax.swing.text.Document document, List<ErrorDescription> errors) {
if(javax.swing.SwingUtilities.isEventDispatchThread()) {
HintsController.setErrors (document, "testsequence", errors);
}
else {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
HintsController.setErrors (document, "testsequence", errors);
}
});
}
}