加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

如何使用InputMap捕获CTRL mouseWheel事件

发布时间:2020-12-14 06:06:22 所属栏目:Java 来源:网络整理
导读:我已经为使用InputMap的Swing应用程序实现了一些热键 getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_A,Event.CTRL_MASK),"selectAll");getActionMap().put("selectAll",new SelectAllAction()); 它工作正常.现在,
我已经为使用InputMap的Swing应用程序实现了一些热键
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,"zoom");

没有运气

谢谢

解决方法

您不能使用InputMap / ActionMap.您需要使用MouseWheelListener.然后,侦听器可以从ActionMap访问自定义Action.这是一个使用“Control 1”进行KeyStroke的简单示例:
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);
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读