1

I'm going through source code of large Swing GUI application. And I've noticed when they want to do something in case focusGained(Focus evn) or focusLost(Focus evn) they always use invokeLater().

Example:

yourTextField.addFocusListener(new java.awt.event.FocusAdapter() {
                public void focusGained(java.awt.event.FocusEvent evt) {
                    SwingUtilities.invokeLater( new Runnable() {
                                    @Override
                                    public void run() {
                                            yourTextField.selectAll();              
                                    }
                            });
                }
            });

Why invokeLater is needed here?

VextoR
  • 5,087
  • 22
  • 74
  • 109
  • 5
    because Focus is pretty asynchronous and invokeLater moving code line xxx.selectAll(); to the end of EDT – mKorbel Jul 10 '14 at 12:19
  • 2
    @mKorbel the comment should be the answer – StanislavL Jul 10 '14 at 12:21
  • @mKorbel, thanks! but I can't understand what does mean focus is asynchronous, and why in this case selectall should be moved to end of EDT? – VextoR Jul 10 '14 at 12:27
  • 2
    Focus is based on peers from Native OS, then is heavy task, this event could be executed in any of part of items in EDT (simple queue), 1st., last, any, then selectAll() can/could/will be executed before focusGained is executed to the GUI (somehow expired as nonsence in EDT qeue), because this JTextField currently hasn't Focus, nor active Caret, invokeLater quite good guarantee that event is moved to the end of queue, the same way I'm suggest to use invokeLater for events from Document (e.g. DocumentListener/Filter) – mKorbel Jul 10 '14 at 13:13
  • 1
    is mentioned in official Oracle tutorial - [How to Use the Focus Subsystem - Timing Focus Transfers](http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html#transferTiming), focus is very lazy – mKorbel Jul 10 '14 at 13:20

0 Answers0