提问者:小点点

Java-使用鼠标滚轮滚动和缩放?


我正在开发一个桌面应用程序,其中我有一个编辑器类,它是一个具有JScrollPane的类的子类。(JScrollPane有两个JScrollBars:水平

            JScrollPane scrollPane = getPanelScrollPane();
            JScrollBar hsb = scrollPane.getHorizontalScrollBar();
            JScrollBar vsb = scrollPane.getVerticalScrollBar();

            MouseWheelListener mwl = new MouseWheelListener() {
                @Override
                public void mouseWheelMoved(MouseWheelEvent e) {
                    if (e.isAltDown()) {
                        double oldZoom = getZoom();
                        double amount = Math.pow(1.1, e.getScrollAmount());
                        if (e.getWheelRotation() > 0) {
                            //zoom in (amount)
                            setZoom(oldZoom * amount);
                        } else {
                            //zoom out (amount)
                            setZoom(oldZoom / amount);
                        }
                    } else {
                        // pass the event on to the scroll pane
                        getParent().dispatchEvent(e);
                    }
                }
            };

            // add mouse-wheel support
            hsb.addMouseWheelListener(mwl);
            vsb.addMouseWheelListener(mwl);

此设置代码正在被调用,但当我移动鼠标滚轮时(当光标在我的视图上时)从未调用mouseWheelMove方法;视图继续滚动(H

我还尝试将“实现MouseWheelListener”和mouseWheelMove方法添加到我的类中:

@Override
public void mouseWheelMoved(MouseWheelEvent e) {
    // (same as mouseWheelMoved above)
}

仍然没有运气…我错过了什么?(编辑:关于传播车轮事件的奖励问题被删除:在这里回答:


共1个答案

匿名用户

想通了…设置代码应该是:

    // add mouse-wheel support
    JScrollPane scrollPane = getPanelScrollPane();
    scrollPane.addMouseWheelListener(this);

然后将实现MouseWheelListener和这个mouseWheelMove方法添加到我的类中:

 @Override
    public void mouseWheelMoved(MouseWheelEvent e) {
        if (e.isAltDown()) {
            double oldZoom = getZoom();
            double amount = Math.pow(1.1, e.getScrollAmount());
            if (e.getWheelRotation() > 0) {
                //zoom in (amount)
                setZoom(oldZoom * amount);
            } else {
                //zoom out (amount)
                setZoom(oldZoom / amount);
            }
        } else {
            // if alt isn't down then propagate event to scrollPane
            JScrollPane scrollPane = getPanelScrollPane();
            scrollPane.getParent().dispatchEvent(e);
        }
    }

现在一切正常!使用alt(选项)向下鼠标滚轮放大/缩小,而不是向下面板滚动!