Search code examples
javacanvaskeyboardswt

Pressing CTRL + mouse Wheel will zoom


When i press CTRL + Scroll mouse wheel at the same time, it works but when I release the CTRL key and continue scrolling it still works. I want it to work only when CTRL and Mouse wheel scroll at same time.

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

                                    }
                                }

                            }
                        });

} 
}

Solution

  • You don't have to add KeyListener. Just check state mask of keyboard button pressed while scrolling. State mask is passed in MouseEvent parameter of MouseScrolled method.

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