Temporarily disable MouseListener

I am working on an assignment with two JPanel

s. One panel contains a moving ball that moves by default, and the other panel has two JRadioButton

that are labeled as On

and Off

. The part I'm stuck on is disabling and enabling MouseListener

( P2.java

) which allows the user to click the panel to reposition the ball. I created functions turnOn

and turnOff

that are triggered with ActionListener

( P1.java

). This starts and stops the ball. I tried to use removeActionListener

, however the compiler throws an error that I cannot use.

Also, it would be easier to use ItemListener

both in this example , so when JRadioButton

already selected, is it ignored?

P1.java

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;
    }
}

      

P2.java

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();
    }

    ...
}

      

The rest of the project

+3


source to share


2 answers


Regardless of your code, I would just use the behavior of the MouseListener depending on its state. I would give it a boolean state variable, like one called enabled, complete with getters and setters, and then short-circuit the code if enabled, false. that is, specific methods might look something like this:

public void mousePressed(MouseEvent mEvt) {
  if (!enabled) {
    return;
  }
  // rest of mousePressed goes here
}

      

Another suggestion, don't do this:



public class P2 extends JPanel implements MouseListener {

      

You don't need your GUI classes to implement your listener interfaces because you are asking the class to do too much. This is fine for toy programs or very small demos, but for larger projects, you'll want to decouple your logic from your kind from your control.

+5


source


You can also use a glass panel to block user interaction



For example: block events

+1


source







All Articles