按 CTRL + 鼠标滚轮将缩放

Pressing CTRL + mouse Wheel will zoom

当我同时按下 CTRL + 滚动鼠标滚轮时,它起作用了 但是当我释放 CTRL 键并继续滚动时它仍然有效。 我希望它只在 CTRL 和鼠标滚轮同时滚动时起作用。

addKeyListener(new KeyListener() {

            @Override
            public void keyPressed(KeyEvent e) {    


               addMouseWheelListener(new MouseWheelListener() {

                            @Override
                            public void mouseScrolled(MouseEvent g) {
                            if(e.keyCode == SWT.CTRL){
                                if(g.count > 0){
                                    System.out.println("up");
                                    int width = getSize().x;
                                    int height = getSize().y;

                                    setSize((int)(width * 1.05), (int)(height * 1.05));


                                }
                                else {
                                    System.out.println("down"); 

                                    int width = getSize().x;
                                    int height = getSize().y;

                                    setSize((int)(width * 0.95), (int)(height * 0.95));

                                    }
                                }

                            }
                        });

} 
}

您不必添加 KeyListener。只需检查滚动时按下的键盘按钮的状态掩码。状态掩码在 MouseScrolled 方法的 MouseEvent 参数中传递。

addMouseWheelListener(new MouseWheelListener() {

    @Override
    public void mouseScrolled(MouseEvent g) {
        if((g.stateMask & SWT.CONTROL) == SWT.CONTROL) {
            performZoom(g.count);
        }
    }
});

这是在按下 CTRL 时使用 mousewheel 缩放 JTextArea 的示例代码:

sourceCodeArea.addMouseWheelListener(mouseWheelEvent ->
{
    if (mouseWheelEvent.isControlDown())
    {
        int scrolled = mouseWheelEvent.getUnitsToScroll();
        Font font = sourceCodeArea.getFont();
        int fontSize = font.getSize();
        fontSize += -(scrolled / 3);
        Font newFont = new Font(font.getFontName(), font.getStyle(), fontSize);
        sourceCodeArea.setFont(newFont);
    }
     else
    {
        sourceCodeArea.getParent().dispatchEvent(mouseWheelEvent);
    }
});
textArea.addMouseWheelListener(mouseWheelEvent -> {
        if (mouseWheelEvent.isControlDown()) {
            textArea.setFont(new Font(
                    textArea.getFont().getFontName(),
                    textArea.getFont().getStyle(),
                    mouseWheelEvent.getUnitsToScroll() > 0
                    ? textArea.getFont().getSize() - 2
                    : textArea.getFont().getSize() + 2));
        }
    });