How would one go about implementing a mouselistener (or some other way, doesn't matter) that will handle a mouse click event at ANY part of the program? Preferably returning to the line it left off at when the click event handler method completes.
I am using swing. The 'context' is a GUI that constantly updates, but must respond to a mouse click from the user at any time with no delay. Indeed I do have experience with events, using and overwriting their handlers etc., not too in-depth I suppose but what i do know has been sufficient in anything until now.
I could not understand your first para, so my answer goes for your second para, if I understood that correctly. ;)
Swing follows single thread model. So, you should be updating the UI from Event Dispatch Thread (EDT). This thread is responsible for delivering the events to your code too, hence the name. If you are continuously updating an UI in a loop then that is going to keep the EDT busy and blocked. The end effect will be an UI which does not respond to user events. This because the events are getting queued and EDT can pick them and deliver them to your code when it becomes free.
Games typically encounter this kind of scenario. You might have noticed that games typically have one fixed rate of refresh which they call FPS (Frames Per Second). Typically maintaining 60 FPS is good enough. That is, you need to draw your UI 50 times per second, but right now it seems that your render loop (which updates the UI) is running continuously.
You need to have separate thread continuously running which is responsible for drawing the UI. This should draw into a buffer (Image). And then invoke repaint() on the UI element to be updated. That UI element's paintComponent() needs to overridden, so that it can copy the image in Image buffer and paint that on the graphics context.
Now comes the real trick. The loop which calls repaint() must do some arithmetic to make sure it does not go beyond drawing 60 times, i.e. looping 60 times, per second. If and when it does then it must call Thread.sleep(sleepTime), where sleepTime is the number of milliseconds left in a second after looping 60 times. It might happen sometime that your loop may take more than a second to complete 60 iterations, then don't just go ahead for next iteration, but call Thread.yield(). This will give other threads a chance to use the CPU, e.g. maybe your EDT. To make the matter more complicated, do not keep yielding always, so might want to put some logic to make sure that yield for only x consecutive times. This last scenario should be very rare, if at all. This scenario means the system is under heavy load.
Remember, repaint() is thread safe and allowed to be called from any thread. It schedules a paint() call on EDT. So, calling repaint() does not guarantee a paint. So, you may want to experiment with different values of FPS to find the one which suites you.
By the way, the trick of rendering to an in-memory Image is technically called Double buffer. This gives us the ability to render nice smooth animations.
Further reading:-
LANSim - Wrote this code a long time back. You can use this code as an example.
http://java.sun.com/docs/books/performance/1st_edition/html/JPSwingThreads.fm.html
Killer Game Programming in Java - This book is on this subject.
Have you looked at SwingWorker? It's a simple framework that lets you run computations in the background and periodically publish updates to the GUI thread.
Related
I'm using 3rd party which drawing to a view something.
I got the process threads list and i found the thread they are using to draw their stuff in.
I want to add my drawing code in this thread - meaning when they are finishing drawing their stuff in the thread then my code will run and then the thread will end (or whatever happens with it).
I tried to do my drawing code in different thread and UI Thread but I can see that my drawing is running after the 3rd party when we change the camera position.
Is it possible to inject some code into another thread? btw, I have only their Thread object in my hand which i got from running over all the threads list.
If not, other solution will be fine also (if there is)
-- EDIT --
Tried to suspend their thread, draw my stuff, and resume, but it is crashing - guess due to those are deprecated functions
Purely theoretical stuff ahead:
Check if they support drawing to backbuffer (not screen) -- OR -- try to redirect drawing to a backbuffer(framebuffer). Do your drawing in the backbuffer too. Manually switch backbuffer (actually back framebuffer) with front framebuffer.
They are most probably doing their drawing in a loop. The onDraw may be event triggered or it just tries to provide as much fps as it can. But if you synchronize the access to your backbuffer, you may force their draw thread to wait exactly for the time you do your drawing and the swap of buffers. You need to initially sync your procedure with theirs (probably by painfully testing that your code gets to run from time to time, and drawing is not blocked). And you must remember that if this work, the synchronization will mean that their thread will wait on their N loop for the end of your N-1 loop at exactly the first operation working with the backbuffer.
I have recently learnt that jMonkey operates on only a single thread which is its openGL render thread. However I'm not able to understand it completely. I can understand that it executes all update and initialize() calls on a single update loop but input should be independent of this update loop, otherwise it will become a polling mechanism.
What exactly happens when the jMonkey application starts. Three tasks that it needs to do is run a update loop, run initialize methods of app states once, do rendering and constantly cater to events? How does it manage all of this via a single thread?
What happens when I add a new app state in the initialize method of another app state?
In input handling input manager notifies the various listeners about events. How are nifty callback events say onClick() are handled on the same render loop?
Lastly in which order this listen- update-render loop runs and where we can find code related to it?
jME uses an approach that's very common in a lot of game engines (and also used in some other user interface libraries such as Swing).
Everything that the game engine does is done in one thread. This can be called the LWJGL thread but as jME can work with alternatives to LWJGL it's more generic to call it the Render Thread or just the jME Thread.
Everything is indeed done on the Render thread, and it does indeed use a polling mechanism. For example if you are holding down the "left" key then each frame the relevant control or app state will be called on the render thread and will move you left by an amount modified by tpf. Tpf is time-per-frame and is very important for keeping smooth movement and letting game systems run at the same speed independently of frame rate.
The only thing within jME3 that commonly uses a separate thread is the Physics Engine. That has a thread that it uses for doing the physics updates and then changes are pushed through to the Render thread using appropriate mechanisms. The system handles this for you though so it is not something you need to worry about.
The thread runs around a game loop. Each time around the loop it checks for things it needs to do (like enqueued tasks, initialize app states, render, etc. It calls update in each active Controller and control, etc). Once it has finished updating everything it then goes on to perform the render. All of this happens every single frame, but computers are so fast that it can still handle all of that and render the game at good frame rates.
That's an implementation detail that you shouldn't need to worry about except to know that it will definitely work. The adding actually gets queued up and handled in the next frame I think.
Everything is handled from the same loop. jME calls through to Nifty to allow Nifty to do its processing. As part of that processing Nifty detects the events and fires off the callback. This means that the callbacks are already coming in on the render thread so you can safely modify the scene graph. jME uses some specially written collections such as SafeArrayList to allow you to modify the scene graph at the same time as iterating over it.
Update, Render, Update, Render, etc. Events firing generally happens as part of the update process when an update is detected. To find the code start by looking in the Application class, you should be able to find the main game loop in there by tracing through from the start() call.
The jME3 Threading Tutorial covers a fair amount of this:
http://hub.jmonkeyengine.org/wiki/doku.php/jme3:advanced:multithreading
I have a GUI(JFrame), with two Buttons and 1 Panel to show the result. One Button is to start the algorithm, one for stopping it. By pressing start, a method is called and it starts running. The runtime of this method varies from couple of seconds to 2-3 minutes, depending on the input.
The problem I have hereby is, by pressing the start-button, the GUI gets completely locked. I cannot press any button till the algorithm terminates. It would be great to be able to stop the algorithm and to visualize parts of the solution after a certain amound of time.
I checked every single line of the Frame, there is nothing that disables it.
//If needed I can provide code, but its pretty long and just some hints and reasons for the problem would be great and I try to fix it by myself.
thanks in advance.
Don't put long-running tasks on the EDT, or the Event Dispatching Thread. Use threading or a SwingWorker instead. Hopefully that's enough google keywords to get you started. :)
It sounds like your algorithm is running in the same thread as the UI components. You probably want to read up on Concurrency and Concurrency in Swing to better understand how to create threads, monitor execution, integrating these concepts with a Swing-based user interface, and so forth. At a very high level, you are going to need to somehow spawn a new thread when your algorithm starts and observe it for intermediate state changes to update the UI. You only want user interface related code running in the event dispatch thread.
I have been trying to find a solution to this question for a while. What is the best practice for writing a swing event buffer? The idea is when triggering an action from a mouse gesture, such as 'mouseMoved', as the events may be fired many times, I only want to trigger the last call - for example,
if the mouse was clicked five times, while the first click listener is being executed, and four are queued, the next call will be the fifth one - all previous ones will be skipped.
It seems that I should be using the Executor class, as it can remove unsubmitted tasks, but I am still not quite sure. All help is appreciated!
user1291492 is right, this shouldn't happen at all. You should never run any code that could take longer than a couple of milliseconds to complete in an event handler. The SwingWorker documentation contains examples and explanations on how to do it. The most important quotes is
Time-consuming tasks should not be run on the Event Dispatch Thread. Otherwise the application becomes unresponsive.
To address the original question, there are two patterns I usually employ:
Use flags to mark actions that should be executed at some point in the future. When there's no other work for some time I check all the flags, reset them and perform the appropriate actions.
When scheduling work for a worker thread, hold a reference to it. Every time before scheduling new work, cancel the previously scheduled work. Most often used with CancellationTokens in C#/Async.
I'm writing a game in Java. And, oh wonder, i have performance issues. I benchmarked the paint itself - 1000 cycles in 3 ms tops. The game logic is even below that. So far, so good. But i still encounter an annoying lag: When scrolling, when zooming, when clicking. The problems get worse when i zoom in and more objects are placed. But still - even when I loop the painting a 1000 times the lags stays more or less the same, so that cant be it.
I tried putting the loop in a task - still the same. I tried pausing the task in between paints - still the same.
Animations run as smooth as silk (since the framerate is stable and high, that makes sense). So how on earth do i organize the inputs in an orderly fashion? Put them all in a seperate thread?
Any input would and will be greatly appreciated!
It sounds like you're using listener callbacks directly on the Swing Event Dispatch Thread, where the UI updates are being done. You should use a command queue, and put events on the queue when a callback is invoked, with the nature of the command, then you use this in the main game update loop that has nothing to do with the EDT.