Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force immediate paint in JavaFX

Tags:

javafx

Is there a way to force a JavaFX app to repaint itself before proceeding? Similar to a Swing Panel's paint(Graphic g) method (I might be getting the keywords wrong there).

Consider the following example: you write a TicTacToe app along with the AI required for a computer player. You would like the ability to show two computer players duke it out. Maybe you put in a two second pause between computer turns to give it a life-like affect. When you hit your "Go" button, there's a large pause of unresponsiveness (the time it takes for the 9 turns to go by with faked pauses for the computer to 'decide') and then suddenly the app's visual is updated in with the completed game's state.

It seems like JavaFX repaints once processing in the app's thread is finished? I'm not completely sure here.

Thanks!

like image 533
Ross Avatar asked Feb 09 '09 14:02

Ross


3 Answers

You are right. JavaFX is event-driven and single-threaded. This means that repaint and event response can not be done simultaneously. Long-running task should be executed on separate thread so they do not block the rendering of the UI, When the task is finished it can sync back to the FX thread by calling FX.deferAction() which will simply execute the code on the main thread.

like image 191
Honza Avatar answered Sep 18 '22 17:09

Honza


This won't be the most helpful answer as I have toyed around with JavaFX for all of half a day, but wouldn't you use Timelines, Keyframes, and binding to accomplish your repaints instead of calling them explicitly like you have described?

See this tutorial for an example.

like image 28
whaley Avatar answered Sep 19 '22 17:09

whaley


JavaFX's model is to separate you from the painting of the "stuff" on the screen. This is very powerful but is a change from how you might be familiar with.

whaley is correct that the appropriate way of doing this in JavaFX is to make a timeline where the move is done every X seconds and will be drawn at that keyframe.

If you have a question about how to do this, try it and make a new question with some code.

like image 33
MattGrommes Avatar answered Sep 21 '22 17:09

MattGrommes