我想在Swing中覆盖鼠标滚轮监听器,但前提是必须按下“控制”按钮。侦听器将附加到JPanel,这样,当他们滚动滚轮时,它将滚动JScrollPane;当按下控制按钮并滚动滚轮时,它将放大。和我自己的听众一起这是我的代码:

mainPanel.addMouseWheelListener(new MouseWheelListener(){
    @Override
    public void mouseWheelMoved(MouseWheelEvent e) {
        if ((e.getModifiers() & InputEvent.CTRL_MASK) == InputEvent.CTRL_MASK) {
            int notches = e.getWheelRotation();

            if (notches < 0) {
                redrawOnZoom(true);
            } else {
                redrawOnZoom(false);
            }
        }
    }
});

有没有这样一种说法:“如果鼠标自行滚动,则执行默认的JScrollPane滚动行为,但如果按下Ctrl,则进行缩放”?

最佳答案

如果您不想处理该事件,则可以将其分派(dispatch)给它的父项:

final MouseWheelListener wheel = new MouseWheelListener() {

    @Override
    public void mouseWheelMoved(MouseWheelEvent e) {
        // handle some events here and dispatch others
        if (shouldHandleHere(e)) {
            LOG.info("do-my-own-stuff");
        } else {
            LOG.info("dispatch-to-parent");
            e.getComponent().getParent().dispatchEvent(e);
        }
    }

    public boolean shouldHandleHere(MouseWheelEvent e) {
        return (e.getModifiersEx() & InputEvent.CTRL_DOWN_MASK) != 0;
    }
};

07-25 21:33