gpt4 book ai didi

java - 如何使用 InputMap 捕获 CTRL + mouseWheel 事件

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:07:24 24 4
gpt4 key购买 nike

我已经为带有 InputMap 的 Swing 应用程序实现了一些热键

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

它工作正常。现在,如果我想 catch

CTRL + MouseWheelUp

我尝试了一些组合,例如

getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(MouseEvent.MOUSE_WHEEL, Event.CTRL_MASK), "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);
}
}

关于java - 如何使用 InputMap 捕获 CTRL + mouseWheel 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6700266/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com