捕获帧内的按键
这似乎是一个简单的行为,但我很难实现它。我正在开发绘制数据图表的软件。我想在用户按回车键时重新绘制图表。更准确地说,我想在用户按 Enter 键并且没有选择文本字段时绘制图表;但现在,每当用户按下回车键时,我都会对绘图感到满意。
我尝试先向框架安装一个基本的 KeyListener,但这不起作用,因为是 JFrame 子级(而不是框架)接收事件。
然后我尝试使用 KeyEventDispatcher,但事实证明它是一个过于全局化的概念。我可以同时在屏幕上显示两个图表,并且可以关闭旧图表或用新图表替换旧图表。使用 KeyEventDispatcher ,我没有简单的方法知道我想从一次打开的多个绘图中激活哪个绘图,并且当前打开的绘图可能不是我实例化时打开的绘图关键调度员。我知道这个解决方案仍然可以工作,但它需要我存储额外的数据,以了解当前处于活动状态的绘图不太适合程序架构。
似乎应该有一种更简单的方法来捕获分派给 JFrame/JPanel
或任何 JFrame
子级的任何 KeyEvents
;但忽略分派到其他帧的事件。优选一种可以添加到框架并因此在框架被废弃时自动废弃的方法。谁能建议一个比我尝试过的更简单的方法?
This seems like a simple behavior, but I'm having difficulty making it happen. I'm working on software which graphs data. I want to redraw the graph when the user hits enter. Well more accurately I want to draw the graph when the user hits enter and doesn't have a text field selected; but for now I'll be satisfied with drawing whenever the user hits enter.
I tried installing a basic KeyListener
to the frame first, but that doesn't work since the JFrame
children, not the frame, receive the event.
I then tried to use the KeyEventDispatcher
, but it's proving too global a concept. I can have two graphs on screen at once, and an old graph can be closed or replaced with a new graph. With the KeyEventDispatcher
I have no easy way of knowing which plot I want to activate out of the multiple plots open at a time and the plots currently open now may not be the plots that were opened when I instantiated the key dispatcher. I know this solution could still work, but it requires my storing extra data as to what plot is currently active that doesn't fit well into the program architecture.
It seems as if there should be an easier method to capture any KeyEvents
dispatched to a JFrame/JPanel
or any of the JFrame's
children; but ignore events dispatched to other frames. Preferable a method that can be added to the frame and thus is automatically disposed when the frame is disposed. Can anyone suggest a simpler method then what I've tried?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要使用 KeyListener。
将 按键绑定 添加到图形面板。
Don't use a KeyListener.
Add a Key Binding to the graph panel.
这非常有效
This works very well