title: How do I use JButton to stop a 'while-loop'
body: <p>To learn some JAVA.
  I have created a simple SwingUI, a frame and a button.
  It should return System.out loop every 2 seconds.
  The button would then stop the loop.
  But it seems to freeze.. <em>go figure</em></p>
  <p>I would like some help on this.
  I do have some books here mostly 'dummies', if you can point out the topic or book title I should read.
  I would be grateful. Thanks.</p>
  <pre><code>/**
   * A basic JFrame with a button to stop 'while-loop'
   */
  public class TestCode {
  
      private boolean runLoop;
  
      public void initFrameUI() {
          // create frame
          JFrame frame = new JFrame();
          frame.setSize(300, 200);
          frame.setVisible(true);
          frame.setLayout(null);
  
          // create button
          JButton button = new JButton();
          frame.add(button);
          button.setBounds(60, 60, 90, 30);
          button.addActionListener(new ActionListener() {
  
              // button click event
              @Override
              public void actionPerformed(ActionEvent e) {
                  runLoop = false;
              }
          });
      }
  
      public void printLoop() {
          while (runLoop) {
              try {
                  Thread.sleep(2000);
                  System.out.println(&quot;Loop-da-loop&quot;);
              } catch (InterruptedException ex) {
                  Logger.getLogger(TestCode.class.getName()).log(Level.SEVERE, null, ex);
              }
          }
      }
  
      public static void main(String[] args) {
          // just a start point
          new TestCode();
      }
  
      public TestCode() {
          // constructor for JFrame
          initFrameUI();
          
          // start the loop
          runLoop = true;
          printLoop();
      }
  }
  </code></pre>