Pressing CTRL + mouse will increase

When I press CTRL + Scroll the 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 the CTRL and mouse keys scroll at the 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));

                                    }
                                }

                            }
                        });

} 
}
+4
source share
2 answers

You do not need to add KeyListener. Just check the state of the mask of the keyboard button pressed while scrolling. The state mask is passed in the MouseEvent parameter of the MouseScrolled method.

addMouseWheelListener(new MouseWheelListener() {

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

Here is a sample code for zooming in JTextAreawith a mousewheelclick CTRL:

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

Source: https://habr.com/ru/post/1610914/


All Articles