2015-10-09 115 views
4

當我按CTRL +同時滾動鼠標滾輪時,它的作用是 ,但是當我釋放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)); 

            } 
           } 

          } 
         }); 

} 
} 

回答

6

您不必添加KeyListener。只需檢查滾動時按下的鍵盤按鈕的狀態掩碼即可。狀態掩碼在MouseScrolled方法的MouseEvent參數中傳遞。

addMouseWheelListener(new MouseWheelListener() { 

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

下面是一個例子代碼來縮放JTextAreamousewheel當按下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); 
    } 
}); 
相關問題