Java - 我们可以在不使用监听器的情况下检测是否按下了某个键吗?
我需要能够检测在我的特定操作期间是否按下了某个键(例如 CTRL)。我无法访问按键侦听器,也无法访问鼠标事件。我希望有一些类具有像“boolean isKeyPressed(keycode)”这样的方法。
有人知道java中有这样的方法吗?
对于一些背景知识,我试图覆盖默认的拖动和拖动。组件的放置行为。默认情况下,根据 DropTargetDragEvent,如果没有按下修饰键,则它会在组件支持的操作列表中查找移动,然后进行复制和复制。然后是一个链接,并在找到第一个链接后停止。
在我的应用程序中,我们支持复制和复制。关联。根据 javadoc,如果不按下 CTRL 键,默认操作是复制。我们希望用户能够指定默认操作(允许他们设置最常用的操作),然后使用修饰键强制执行特定操作。
如果我可以检测到按键状态,那么我可以强制发生这种情况,但我看不到任何其他更改默认操作的方法。
预先感谢,布莱恩
I need to be able to detect if a certain key (e.g. CTRL) is pressed during a specific operation of mine. I don't have access to a key listener, nor to a mouse event. What I'm hoping is that there will be some class that has a method like "boolean isKeyPressed(keycode)".
Is anyone aware of a method like this in java?
For a bit of background, I am trying to override the default drag & drop behaviour for a component. By default, according to the javadocs for DropTargetDragEvent, if no key modifier is pressed, then the it looks in the component's supported actions list for a move, then a copy & then a link and stops after finding the first one.
In my application, we support both copy & link. As per the javadoc, without the CTRL key pressed, the default action is copy. We want the user to be able to specify the default action (allowing them to set their most commonly used) and then force a specific one using the modifier keys.
If I can detect the key pressed state then I can force this to happen but I can't see any other way of changing the default action.
Thanks in advance, Brian
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
MouseEvent.getModifiers()
方法将返回生成MouseEvent
时按下的修饰键的位图。或者,您可以使用MouseEvent.isControlDown()
来专门检查 CTRL 键。The
MouseEvent.getModifiers()
method will return a bitmap of modifier keys that are pressed at the time theMouseEvent
was generated. Or, you could useMouseEvent.isControlDown()
to check specifically the CTRL key.这可能是一种肮脏的方式。但这允许您“记录”关键事件然后查询它们。
This is a possibly dirty way to go about it. But this allows you to 'record' key events and then query them.
即使有这样的方法,你想用它做什么?无限循环地调用它,希望它在某个时刻返回 true?我认为基于事件/基于侦听器的机制更适合这种情况。
Even if there was such a method, what do you want to do with it? Call it in an endless loop in the hope it returns true at some point? I think an event-based / listener-based mechanism suits much better in this case.
我认为你处理这个问题的方式是错误的。您想要做的是在开始拖动时更改操作,而不是在拖动时更改操作。有多种方法可以更改启动时的操作,包括在“无修饰符”情况下询问用户首选项。可以更改 DropTargetDragEvent 的调用方式。
I think you are going about this the wrong way. What you want to do is change the action when the drag is initiated, not when it is dropped. There are ways to change what the action is on initiation, including interrogating the user preferences in the "no modifiers" case. It's possible that changing the way the DropTargetDragEvent is called.