title: Closing JFrame on Mouse Click
body: <p>Hey guys, I want my JFrame to close on a mouse click. I have code to do it, but it isn't working...</p>
  
  <pre><code>public void closeFrame ()
  {
  
      jPanel.removeAll ();
      String x = "";
      JLabel exit = new JLabel ("Click Anywhere To Close!", JLabel.CENTER);
      exit.setPreferredSize (new Dimension (700, 100));
      jPanel.add (exit);
      jPanel.revalidate ();
  
      MouseListener ml = new MouseAdapter ()
      {
          public void mouseClicked (MouseEvent event)
          {
              //Put JFrame close code here
              dispose ();
              System.exit (0);
          }
      }
      ;
      addMouseListener (ml);
      validate (); //This hasn't made a difference :(
  
  }
  </code></pre>
  
  <p>The class extends JFrame and it DOESNT implement MouseListener. Nonetheless, the code doesn't work.</p>
  
  <p>This is what the initialization of the JFrame looks like (hope it helps)...</p>
  
  <pre><code>public void createFrame ()
  {
      new JFrame (":) :)");
      setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
      setVisible (true);
      //Some Initialization for jPanel variable
      getContentPane().add(jPanel);
      pack();
  }
  </code></pre>
  
  <p>How can I make this code work &amp; if I can't, is there an alternate way of closing on mouse click?</p>
  
  <p>---EDIT---</p>
  
  <p>Thanks goes to Hovercraft Full Of Eels</p>
  
  <p>The MouseListener must be added to the JPanel</p>
  
  <pre><code>//WORKING CODE
  public void closeFrame ()
  {
  
      jPanel.removeAll ();
      String x = "";
      JLabel exit = new JLabel ("Click Anywhere To Close!", JLabel.CENTER);
      exit.setPreferredSize (new Dimension (700, 100));
      jPanel.add (exit);
      //jPanel.revalidate ();
  
      MouseListener ml = new MouseAdapter ()
      {
          public void mouseClicked (MouseEvent event)
          {
              //Put JFrame close code here
              dispose ();
              System.exit (0);
          }
      }
      ;
      jPanel.addMouseListener (ml);
      jPanel.revalidate ();
  
  }
  </code></pre>