It is probably best to explain what you are trying to do. In general, the event dispatch system is designed in such a way that you do not need to know or worry about its internal components. If you are writing an event handler that directly updates the user interface, then it makes sense not to use Runnable and perform your inline updates. However, if the event handler does some computation or processing that takes an indefinite amount of time, then you will want to use a thread that will ultimately perform a user interface update using Runnable with a call to Swing.invokeLater. The need to know the sequence of events as they are sent means that you are trying to build assumptions in your logic that probably belong elsewhere.
For example, consider a mouse click event handler that performs heavy processing (network downloads or DBMS requests) in a stream, and then updates the text label in the user interface. You probably want to make sure that the process of processing and updating the user interface occurs before the user clicks elsewhere in the user interface to avoid the ambiguity of click processing. In this case, you are likely to disable the user interface or certain elements of the interactive interface immediately after the first mouse click, so that the user interface remains responsive, but protects the onMouse handler from re-entry until the original click event is fully processed. (forgive the following snippet, since many years have passed since I did Swing, this is more like pseudo-code.)
void setUIEnabled(boolean enable) { for(Button eachUIButton : getAllClickableButtons()) { eachUIButton.setEnabled(enable); } } void onMouseClick(MouseEvent event) { setUIEnabled(false); new Thread( new Runnable() { public void run() { final String result = doLengthyProcessing(); enableRunnable = new Runnable() { public void run() { setUIEnabled(true); updateTextLabelFromLengthyProcess(result); } }; Swing.invokeLater(enableRunnable); } } ).start(); }
The idea here is that you write the logic in such a way that it does not depend on the random order of sending events, but recognizes that processing will probably take longer than the next incoming mouse event, and will include such terms. Subtle improvement was would also draw a progress indicator or performance counter to indicate that work is being done with the user.
Cliff
source share