Stage stage = (Stage) closeButton.getScene().getWindow();
stage.close();
}
This will find the stage that contains the close button and close that stage.
A potentially far better way of working with dialogs is to use the Dialog capabilities of the Open
Source toolkit known as ControlsFX.
See also:
• org.controlsfx.dialog.Dialogs
JavaFX Tasks, Services and Workers
Access to JavaFX can only be performed from the UI thread also called the JavaFX Application
thread. It is invalid to attempt to manipulate JavaFX resources from within the context of other
threads. Putting it another way, JavaFX is not thread safe. Calling JavaFX from other threads can
result in grossly unpredictable results.
However, if we try and follow these rules and attempt to perform all our processing work within the
UI thread we will find another problem. The application will appear sluggish and perform badly.
JavaFX provides a package called javafx.concurrent which is specifically designed to allow
background tasks to be performed while keeping the UI thread safe,
See also:
• Concurrency in JavaFX – Java SE 8
Running work in the background
Imagine that we wish to do some non UI processing that takes some time and, when done, update
the UI. An example of this might be an expensive database query or a Web Service call. We may
want to do this on as the result of a button press or other UI interaction. If we now look at the
diagrams show below. The top half shows the normal flow of operation. The Main thread has
control and when a user clicks a button, the App Callback is invoked on that thread. The App
Callback then makes its slow call to the back-end blocking waiting for the return. When the back-
end completes, the App Callback does some work and finally returns control to the main thread. As
we can see, the main thread gave up control for the whole duration.
If we now look at the second diagram, again the main thread calls the App Callback logic but this
time, the App Callback logic creates a new thread that gets control. The App Callback thread
immediately returns control to the Main thread which can continue to update the UI. We now have
two threads executing in parallel with each other. The worker thread now makes the slow call to
the back end and when it returns, it returns control to the worker thread. Because of contractual
rules, the worker thread may not update any UI. That is the exclusive prerogative of the Java FX
main thread. The worker thread then issues a request to the main thread to run some logic at some
time later and the worker ends. At some later point, the main thread is now able to invoke the
specified logic that the worker thread asked it to call. That logic executes on the main thread in the
App Callback code.
The vitally important thing to note is that the JavaFX thread did NOT have to wait anywhere near
as long as that duration shown in the first diagram.
Page 263
Kommentare zu diesen Handbüchern