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

时间:2017-05-21 01:03:12

标签: java netbeans scroll zoom mousewheel

我正在netbeans中开发一个桌面应用程序,其中我有一个编辑器类,它是一个具有JScrollPane的类的子类。 (JScrollPane有两个JScrollBars:水平和垂直。)一切都按预期工作,包括能够垂直(无修饰符)和水平(通过使用移位修改器)滚动鼠标滚轮。 另一个超级类(在我的类和JScrollPane类之间)通过菜单命令设置缩放(缩放)因子来实现缩放(可以正常工作(包括滚动))。 我想要的是当alt(选项)键关闭时(isAltDown()为真)能够通过鼠标滚轮放大/缩小,否则回退到默认滚动(H& V)行为。这是我的课程设置代码的一部分:

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

这个设置代码被调用,但是当我移动鼠标滚轮时(当光标在我的视图上时),永远不会调用mouseWheelMoved方法;视图继续正常滚动(H& V)。

我也尝试在课堂上添加“implements MouseWheelListener”和mouseWheelMoved方法:

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

仍然没有运气......我错过了什么? (编辑:关于传播轮播事件的奖励问题:在此处回答:< How to implement MouseWheelListener for JPanel without breaking its default implementation?>)。

1 个答案:

答案 0 :(得分:1)

想出来......设置代码应为:

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

然后将implements MouseWheelListener和此mouseWheelMoved方法添加到我的班级:

 @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(选项)按下鼠标滚轮放大/缩小,并且不按下面板滚动!