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.
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
}
});
While debugging a strange behaviour in Swing I found this tools:
CheckThreadViolationRepaintManager edited version by Alex Ruiz. (You must understand what this class does before answering my Question, thanks)
And i fount a thread violation in my code but i dont understand why because I use SwingUtilities.invokeAndWait() everywhere.
Here is the code that cause threadViolation. Only last line cause the bug:
protected void display() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
asyncDisplay();
}
});
}
private void asyncDisplay(){
System.out.println("is in edt: " + SwingUtilities.isEventDispatchThread());
this.printedComponent.setVisible(true);
this.printedComponent.setOpaque(false);
this.setVisible(true);
}
And the result:
is in edt: true
exception: java.lang.Exception
java.lang.Exception
at fr.numvision.common.CheckThreadViolationRepaintManager.checkThreadViolations(CheckThreadViolationRepaintManager.java:31)
at fr.numvision.common.CheckThreadViolationRepaintManager.addDirtyRegion(CheckThreadViolationRepaintManager.java:25)
at javax.swing.JComponent.repaint(JComponent.java:4795)
at java.awt.Component.imageUpdate(Component.java:3516)
at javax.swing.JLabel.imageUpdate(JLabel.java:900)
at sun.awt.image.ImageWatched$WeakLink.newInfo(ImageWatched.java:132)
at sun.awt.image.ImageWatched.newInfo(ImageWatched.java:170)
at sun.awt.image.ImageRepresentation.setPixels(ImageRepresentation.java:533)
at sun.awt.image.ImageDecoder.setPixels(ImageDecoder.java:126)
at sun.awt.image.GifImageDecoder.sendPixels(GifImageDecoder.java:447)
at sun.awt.image.GifImageDecoder.parseImage(Native Method)
at sun.awt.image.GifImageDecoder.readImage(GifImageDecoder.java:596)
at sun.awt.image.GifImageDecoder.produceImage(GifImageDecoder.java:212)
at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:269)
at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:205)
at sun.awt.image.ImageFetcher.run(ImageFetcher.java:169)
I really dont understand why this.setVisible(true); cause thread violation (this is a JComponent) while this.printedComponent.setVisible(true); dont.
Thanks,
The code which caused the exception is not synchronous with your this.setVisible(true); line. That line just flags the component as needing a repaint, and the actual repaint event comes in later, afer setVisible() has returned. What seems to be going on is that some other code, somehow causally related to the repainting of your component, submits some GUI code to an external thread.
The details of all this are impossible to derive from the amount of code you have posted.
I'm trying to do an incremental display of a Component because it takes too much time to make all the calculations. So i don't want to freeze the graphic interface i'd like to display my image ( a fractal ) every 2.3 seconds. The function which calculate all the points is compute. Before i want to make the incremental display this method was calculating all points. Now it only calculates 10000 points.
class FlameBuilderPreviewComponent:
Timer timer1=new Timer(1000,new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
time=time+10000;
fa= builder.build().compute(density,frame,getWidth(),getHeight(),accumulator);
}
});
timer1.start();
for (int z = 0; z <fa.height(); z++) {
for (int j = 0; j < fa.width(); j++) {
image.setRGB(j,z,fa.color(palette, background, j, fa.height()-1-z).asPackedRGB());
}
}
g0.drawImage(image,0,0,null);
if (time>density*getWidth()*getHeight()){
timer1.stop();
}
Then the other part of the program is the GUI interface, i put another timer this one is responsible of repainting the image.
class FlameMakerGUI :
fBPC=new FlameBuilderPreviewComponent(builder, background, palette, r1, density);
Timer timer = new Timer(2500,new ActionListener(){
public void actionPerformed(ActionEvent e) {
fBPC.repaint();
System.out.println("titi");
}
});
timer.start();
fractale.add(fBPC,BorderLayout.CENTER);
Then this is the error that the program show each time timer is executed:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at ch.epfl.flamemaker.gui.FlameBuilderPreviewComponent.paintComponent(FlameBuilderPreviewComponent.java:82)
at javax.swing.JComponent.paint(JComponent.java:1054)
at javax.swing.JComponent.paintChildren(JComponent.java:887)
at javax.swing.JComponent.paint(JComponent.java:1063)
at javax.swing.JComponent.paintToOffscreen(JComponent.java:5221)
at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(RepaintManager.java:1512)
at javax.swing.RepaintManager$PaintManager.paint(RepaintManager.java:1443)
at javax.swing.RepaintManager.paint(RepaintManager.java:1236)
at javax.swing.JComponent._paintImmediately(JComponent.java:5169)
at javax.swing.JComponent.paintImmediately(JComponent.java:4980)
at javax.swing.RepaintManager$3.run(RepaintManager.java:796)
at javax.swing.RepaintManager$3.run(RepaintManager.java:784)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:784)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:757)
at javax.swing.RepaintManager.prePaintDirtyRegions(RepaintManager.java:706)
at javax.swing.RepaintManager.access$1000(RepaintManager.java:62)
at javax.swing.RepaintManager$ProcessingRunnable.run(RepaintManager.java:1651)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:727)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:688)
at java.awt.EventQueue$3.run(EventQueue.java:686)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:697)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
Thank you for helping
You are creating a action listener every second, that doesn't make any sense. You obviously do not understand how event listeners work or how the Timer class works.
Also, tasks on the EDT (event dispatch thread) must finish quickly; if they don't, unhandled events back up and the user interface becomes unresponsive
You need to use Swing Worker in order to archive proper concurrency.
From the Oracle website:
Swing consists of three kinds of threads:
Initial threads, the threads that execute initial application code.
The event dispatch thread, where all event-handling code is executed. Most code that interacts with the Swing framework must also
execute on this thread.
Worker threads, also known as background threads, where time-consuming background tasks are executed.
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
I'm honestly not sure if the title fits the question completely, but here it is anyway. I'm making a simple game in java where alien spaceships fall down from the top of the screen and if you don't kill them and they get to the bottom of the screen, the space station takes damage. But whenever the space station gets destroyed, the message-box that should tell the player that they died, won't stop appearing, it just keeps popping up over and over again. And in the console I get an error message that won't stop getting bigger! This is the code I have for the space station's health:
public class SpaceStation extends Entity {
public static int stationHealth = 100;
public SpaceStation(int x, int y) {
super(x, y);
}
public void update() {
}
public void draw(Graphics2D g2d) {
g2d.drawImage(ImageLocator.getSpaceStation(), 0, 595, null);
// HEALTH BAR
g2d.fillRect(5, 25, stationHealth, 10);
if(stationHealth <= 0) {
try{
JOptionPane.showMessageDialog(null, "You died on level "
+ GameFrame.level + ". Better luck next time!");
GameFrame.mainTimer.stop();
System.exit(0);
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e.getMessage());
System.exit(0);
}
}
}
public Rectangle getBounds() {
return new Rectangle(x, y, 600, 200);
}
}
Apparently the line that the error is on is the JOptionPane.showMessageDialog(null, "You died on level "
Here's the error message:
at java.lang.Thread.run(Unknown Source)
Exception in thread "AWT-EventQueue-0" java.lang.InternalError: The current process has used all of its system allowance of handles for Window Manager objects.
at sun.awt.windows.WToolkit.eventLoop(Native Method)
at sun.awt.windows.WToolkit.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Exception in thread "AWT-EventQueue-0" java.lang.InternalError: The current process has used all of its system allowance of handles for Window Manager objects.
Thank you for your time.
Don't open a dialog from within the paint method! Or perhaps more domain specific, don't do that in a method that might be called from the paint method of another class, as the draw(Graphics2D) suggests.
I can only presume your code has a timer that calls repaint(), which in turn might cause a call to paint(Graphics) or paintComponent(Graphics). But that is also done by the JRE itself whenever it knows a component might have an element appear over the top, ..like a JOptionPane. Hence 'infinite loop'.