java - 暂时禁用 MouseListener

标签 java swing jpanel

我正在处理两个 JPanel 的作业。一个面板包含默认移动的移动球,另一个面板有两个标记为 OnOffJRadioButton。我坚持的部分是禁用和启用 MouseListener (P2.java),它允许用户在面板上单击以重新定位球。我创建了使用 ActionListener (P1.java) 触发的函数 turnOnturnOff。这开始和停止球。我已尝试使用 removeActionListener,但编译器抛出错误提示我无法使用该方法。

此外,使用 ItemListener 会更容易,例如 this example这样,当 JRadioButton 已被选中时,它会被忽略吗?

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

    ...
}

项目的其余部分

最佳答案

在不查看您的代码的情况下,我只会让我的 MouseListener 的行为取决于它的状态。我会给它一个状态 boolean 变量,比如称为 enabled,包含 getter 和 setter,然后如果 enabled 为 false,则将代码短路。即,具体方法可能类似于:

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

另一个建议,不要这样做:

public class P2 extends JPanel implements MouseListener {

不要让您的 GUI 类实现您的监听器接口(interface),因为您要求该类做太多事情。这对于玩具程序或非常小的演示程序来说是可以的,但对于较大的项目,您将希望将逻辑与 View 和控件分开。

关于java - 暂时禁用 MouseListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14699430/

相关文章:

java - 在面板上添加ActionListener。如何映射到主框架?

java - 防止覆盖 guice 中已经绑定(bind)的类

java - Scala - 非法的 base64 字符 5c

java - 在用户目录中打开 javafx FileChooser

java - Win 上带有 JMenuItem setHorizo​​ntalTextPosition 的双图标

java - JFrame和JPanel之间的通信

java - 改变 textView 的布局引力

java - JOptionPane.showConfirmDialog 阻止后台窗口

java - 在 JSplitPane 中调整 JPanel 的大小

java - 如何在多页中打印一个大的 JPanel