title: Temporarily disable MouseListener
body: <p>I'm working on assignment with two <code>JPanel</code>s. One panel contains a moving ball which moves by default and the other panel has two <code>JRadioButton</code>s that are labeled <code>On</code> and <code>Off</code>. The part that I'm stuck on is disabling and enabling the <code>MouseListener</code> (<code>P2.java</code>) that allows the user to click on the panel to reposition the ball. I've created functions <code>turnOn</code> and <code>turnOff</code> that are triggered using an <code>ActionListener</code> (<code>P1.java</code>). This starts and stops the ball. I've tried to use <code>removeActionListener</code>, however the compiler throws the error that I'm not able to use the method.</p>
  
  <p>In addition, would be easier to use an <code>ItemListener</code> like in <a href="http://www.java2s.com/Code/Java/Event/ItemListenerforJRadioButton.htm" rel="nofollow">this example</a> so that when the <code>JRadioButton</code> is already selected it is ignored?</p>
  
  <p><strong>P1.java</strong></p>
  
  <pre><code>import java.awt.*;
  import javax.swing.*;
  import java.awt.event.*;
  
  public class P1 extends JPanel
  {
      private JRadioButton on = new JRadioButton("On", true);
      private JRadioButton off = new JRadioButton("Off");
  
      public P1()
      {
          ButtonGroup group = new ButtonGroup();
          group.add(on);
          group.add(off);
  
          add(on);
          add(off);
  
          ButtonHandler bh = new ButtonHandler();
          on.addActionListener(bh);
          off.addActionListener(bh);
      }
  
      private class ButtonHandler implements ActionListener
      {
          public void actionPerformed(ActionEvent ae)
          {
              if(ae.getSource() == on) turnOn();
  
              if(ae.getSource() == off) turnOff();
          }
      }
  
      public static void turnOn () {
          Ball.dx = 1;
          Ball.dy = 1;
      }
  
      public static void turnOff () {
          Ball.dx = 0;
          Ball.dy = 0;
      }
  }
  </code></pre>
  
  <p><strong>P2.java</strong></p>
  
  <pre><code>import java.awt.*;
  import javax.swing.*;
  import java.awt.event.*;
  
  public class P2 extends JPanel implements MouseListener
  {
      public P2()
      {
          super();
          addMouseListener(this);
      }
  
      public void mousePressed(MouseEvent e)
      {
          ball.x = e.getX();
          ball.y = e.getY();
          repaint();
      }
  
      ...
  }
  </code></pre>
  
  <p><strong>Rest of the project</strong></p>
  
  <ul>
  <li><a href="http://pastebin.com/SQTieJ1j" rel="nofollow"><code>myFrame.java</code></a></li>
  <li><a href="http://pastebin.com/negBAiem" rel="nofollow"><code>ball.java</code></a></li>
  </ul>