Dardan Kryeziu
Dardan Kryeziu

Reputation: 21

JavaFX: Make LocalDateTime fire Event?

I want to automate an online game. It worked while it was only terminal based. But I wanted to add an JavaFX UI and now I don't know where to put Thread.waits until a certain LocalDateTime is reached. Where does JavaFX wait for it's events (like button clicks, ...) and can I overwrite that method? Or is there a way to create custom LocalDateTime events and listeners for javaFX?

If i add a Thread.wait in initialize() the whole scene doesn't appear until that certain LocalDateTime is reached.

Upvotes: 0

Views: 145

Answers (1)

Basil Bourque
Basil Bourque

Reputation: 338815

If you want to have an event fire at some predetermined moment, but you want the user-interface of the app to remain responsive to the user’s actions, then you need a background thread. You should almost never sleep the GUI thread of your app, as that makes your app unresponsive and appear to be crashed. For fun, try it the wrong way: Drop a Thread.sleep call into your GUI code to see how it temporarily freezes your app.

Learn about concurrency. Start with the Oracle Tutorial, and work your way up to eventually making an annual read of the Bible, Java Concurrency in Practice by Goetz et al.

The Executors framework was built to make threading easier. Specifically, you will want the ScheduledExecutorService class. This has been covered many many times already on Stack Overflow. Search to learn more.

And learn about how to properly interact with the GUI thread from a background thread.

Never use LocalDateTime to track a moment, as explained in the class doc. For a moment, use Instant, OffsetDateTime, or ZonedDateTime. For a span-of-time on the scale of hours-minutes-seconds, use Duration. The Duration class offers methods such as toMinutes, toSeconds, the results of which you can feed as your delay to a ScheduledExecutorService. All of these classes have been covered many many times on Stack Overflow. Search to learn more.

Upvotes: 2

Related Questions