0

This is simple code to create a button. There is one thing that I don't understand: why are we using SwingUtilities.InvokeLater(new Runnable()).

Please make the answer as simple as possible so that I can grasp it easily.

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilies; 

public class button {

    public static void main(String args[]) {
        SwingUtilies.InvokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame();
                JButton button = new JButton("ok");

                frame.add(button);
                frame.setDefault.CloseOperation(JFrame.DISPOSE_ON_CLOSE);
                frame.Pack();
                frame.setVisible(true);
            }
        });
    }
}
Barett
  • 5,826
  • 6
  • 51
  • 55
user187744
  • 71
  • 1
  • 1
  • 7
  • Can you explain it with reference to my code please – user187744 Aug 19 '15 at 19:56
  • Are you willing to do *any* work **yourself**? – PM 77-1 Aug 19 '15 at 19:57
  • http://stackoverflow.com/questions/3551542/swingutilities-invokelater-why-is-it-needed – persistent_poltergeist Aug 19 '15 at 19:58
  • Swing is a single threaded framework, but, it operates in its own thread. There is no guarantee what thread main will be called in, so you are required to synchronise your ui code with the event dispatching thread, this prevents possible graphics glitches as well as possible thread deadlocks on some OSs – MadProgrammer Aug 19 '15 at 21:28

1 Answers1

2

It is because the event loop in Swing is single threaded and all Swing events run off that same loop.

If you run the button's graphics from the application's main thread then it could conflict with other UI actions taking place on Swing event dispatch thread.

To synchronize the button activities with other activities so that it takes place only after all other Swing tasks are done, invokeLater is used to schedule the button's activities to take place on the event dispatch thread.

Tyler Durden
  • 11,156
  • 9
  • 64
  • 126
  • No, this is wrong. `SwingUtilities.invokeLater` makes sure that the `Runnable` is executed on the event dispatch thread, not on its own thread. So the problem you mention is not solved by `invokeLater`. – Hoopje Aug 19 '15 at 20:10
  • @Hoopje I updated my answer. – Tyler Durden Aug 19 '15 at 20:37