2011-07-14 103 views
6

我已經實現了一些快捷鍵與InputMap的Swing應用程序一樣如何捕捉CTRL +鼠標滾輪事件與InputMap的

getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_A, Event.CTRL_MASK), "selectAll"); 
getActionMap().put("selectAll", new SelectAllAction()); 

它的正常工作。現在,我該怎麼做同樣的事情,如果我想趕上

CTRL + MouseWheelUp

我已經嘗試了一些組合,如

getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(MouseEvent.MOUSE_WHEEL, Event.CTRL_MASK), "zoom"); 

沒有運氣

謝謝

回答

6

對此,您無法使用InputMap/ActionMap。您需要使用MouseWheelListener。偵聽器可以從ActionMap中訪問自定義Action。下面是一個使用「控制1」擊鍵一個簡單的例子:

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

public class MouseWheelTest extends JPanel implements MouseWheelListener { 
    private final static String SOME_ACTION = "control 1"; 

    public MouseWheelTest() { 
     super(new BorderLayout()); 

     JTextArea textArea = new JTextArea(10, 40); 
     JScrollPane scrollPane = new JScrollPane(textArea); 
     add(scrollPane, BorderLayout.CENTER); 
     textArea.addMouseWheelListener(this); 

     Action someAction = new AbstractAction() { 
      public void actionPerformed(ActionEvent e) { 
       System.out.println("do some action"); 
      } 
     }; 

     // Control A is used by a text area so try a different key 
     textArea.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) 
      .put(KeyStroke.getKeyStroke(SOME_ACTION), SOME_ACTION); 
     textArea.getActionMap().put(SOME_ACTION, someAction); 
    } 

    public void mouseWheelMoved(MouseWheelEvent e) { 
     if (e.isControlDown()) { 
      if (e.getWheelRotation() < 0) { 
       JComponent component = (JComponent)e.getComponent(); 
       Action action = component.getActionMap().get(SOME_ACTION); 
       if (action != null) 
        action.actionPerformed(null); 
      } else { 
       System.out.println("scrolled down"); 
      } 
     } 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       createAndShowGUI(); 
      } 
     }); 
    } 

    private static void createAndShowGUI() { 
     JFrame frame = new JFrame("MouseWheelTest"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.add(new MouseWheelTest()); 
     frame.pack(); 
     frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 
    } 
} 
+0

感謝爲+1 – mKorbel

0

嘗試InputEvent.CTRL_DOWN_MASK而不是Event.CTRL _面具。根據JavaDoc:「建議使用CTRL_DOWN_MASK來代替。」

+0

我試了一下,同樣的事情 – outellou

1

在我的情況,我想聽聽JPanel所以很容易使用MouseWheelListener

這裏是我的代碼:

@Override 
public void mouseWheelMoved(MouseWheelEvent e) {  
    if (e.isControlDown()) { 
     if (e.getWheelRotation() < 0) {    
      System.out.println("Zoom-in when scrolling up"); 
     } else { 
      System.out.println("Zoom-out when scrolling down");    
     } 
    }  
} 

感謝

+0

謝謝,這是這裏最好的答案。 –