停用默认 java JSlider 鼠标回调

Deactivate default java JSlider mouse callbacks

你如何停用例如JSlider 组件上的 mouseReleased 事件回调?

您可以覆盖 JSlider,启用 属性。添加鼠标侦听器时,创建一个委托给原始鼠标侦听器的新鼠标侦听器,但仅当启用 属性 时:

import javax.swing.JSlider;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

class MyJSlider extends JSlider
{
    private boolean isEnabled = true;

    public void setEnabled(boolean isEnabled)
    {
        this.isEnabled = isEnabled;
    }

    @Override
    public synchronized void addMouseListener(final MouseListener delegate)
    {
        super.addMouseListener(
            new MouseListener() {
                @Override
                public void mouseClicked(final MouseEvent e) {
                    delegate.mouseClicked(e);
                }

                @Override
                public void mousePressed(final MouseEvent e) {
                    delegate.mousePressed(e);
                }

                @Override
                public void mouseReleased(final MouseEvent e) {
                    if (isEnabled) {
                        delegate.mouseReleased(e);
                    }
                }

                @Override
                public void mouseEntered(final MouseEvent e) {
                    delegate.mouseEntered(e);
                }

                @Override
                public void mouseExited(final MouseEvent e) {
                    delegate.mouseExited(e);
                }
            }
        );
    }
}

我通常只是在 class 中添加针对本地布尔标志的侦听器检查,然后再处理我打开或关闭的侦听器的其余部分,以确定是否应处理侦听器。