When I start my GUI interfaces, what can happen if I don't use invokeLater?
- Does that mean all rest of the GUI paints/updates/etc. will be in the main thread?
- Will calling a
repaint
outside of aninvokeLater
make all subsequent calls fall into the main thread?
Basically this:
void main()
{
JFrame jmf();
setVisible(jmf);
}
------------- VS -------------
void main()
{
SwingUtilities.invokeLater(new Runnable(){
run(){
JFrame jmf();
setVisible(jmf);
}
}
});
NOTE: In cases with small GUI, I if I don't put the invokeLater
it seems to work fine. And in fact the application doesn't terminate although the last line of the main
is executed.
I have read quite a few articles on why we should use it pertaining to the fact that Swing is not thread safe (it is single threaded and so on), but I really didn't read the repercussions of not calling invokeLater
(partially because of my limited knowledge in Threads)
The reality is, nothing might happen or the world will end. It's next to near impossible to predicate, this is the nature of multi-threaded environments...
Unless you are doing some really dynamic setups, until the a frame is made visible it "should" be okay not to do it within the context of the EDT.
The problem comes down to the fact that different platforms are implemented differently (at the native level). For example, the original requirement for using invokeLater when starting your UI seems to have come from deadlocks on the Sun OS many years back.
I've also seen some issues with Java 7 (but my predecessors idea of the thread was weird to say the least). The general advice is, use invokeLater to create and display your UI. Run all UI code within the context of the EDT
It will also reduce the risk of you having to spend weeks trying to replicate and track down those weird anomalies (by running you all you UI code from within the EDT)
Updated based on comments from the OP
repaint
makes a request to theRepaintManager
, that makes decisions about what and when something should be paint. It will actually post a "paint" event directly on to the Event Queue, which is then processed by the Event Dispatching Thread, so repaint is actually on (of the few) thread safe methods...Take a look at
The general advice would be, you should use
invokeLater
because that's how the API has been designed, doing anything else is inviting problems...