0

In my program, I am calling a constructor for a JFrame and several components and immediately afterwards, I am calling a method doing heavy computing and locking the CPU for several seconds. Because of this and because both the JFrame and that method are in the same Thread, the JFrame will not composite properly until after the method is finished.

Window window = new Window(); //Window extends JFrame and adds several components to it
calculatePiOrWhatever();
Andreas Hartmann
  • 1,825
  • 4
  • 23
  • 36
  • 6
    Use a `SwingWorker`. – Andrew Thompson Jun 28 '14 at 12:06
  • 2
    To elaborate on @AndrewThompson's comment, the key is to any long-running tasks in a background thread off of the Swing event thread. A SwingWorker is one way to do this that is optimized for safe Swing interactions. It also acts as a returnable Future, and so can be used to return the result of a calculation. – Hovercraft Full Of Eels Jun 28 '14 at 12:17
  • 1
    For example, please look at my answer to [this question](http://stackoverflow.com/questions/20423980/execute-process-in-java-without-jframe-freezing). – Hovercraft Full Of Eels Jun 28 '14 at 12:28
  • Oops, "the key is to **do** any long-running tasks in a background thread..." – Hovercraft Full Of Eels Jun 28 '14 at 12:36
  • 3
    You title doesn't make sense. You don't have to wait for a constructor to finish. It won't return until it *has* finished. Your actual question is about how *not* to wait until the computational method you wish to call *next* has finished. – user207421 Jun 28 '14 at 12:36
  • http://www.javacodegeeks.com/2012/12/multi-threading-in-java-swing-with-swingworker.html This site explains using SwingWorker class with very basic example step by step, you should have a look at it. – nihirus Jun 28 '14 at 23:49

0 Answers0