gpt4 book ai didi

java - 如何使 Swing JTextArea 响应 KeyEvents?

转载 作者:行者123 更新时间:2023-12-01 18:59:07 25 4
gpt4 key购买 nike

我有一个JTextArea我的 Swing 代码中包含一个组件,我想添加一个处理程序/监听器,每当用户在 JTextArea 中键入(按键事件;向上键、向下键等)文本时就会触发该处理程序/监听器。

根据上面的JavaDocs,我可以在其内部添加一个DocumentListener文档模型。但是,当我实现 DocumentListener 时,我必须编写以下实现:

  • 删除更新
  • 插入更新
  • 更改更新

这些不是我期望看到的方法类型!我期望看到像onKeyDown(KeyEvent e)onKeyUp(KeyEvent e等)这样的方法。

所以我问:如何让我的 JTextArea 响应按键向上/向下事件?提前致谢!

最佳答案

这可能是使用按键绑定(bind)的好情况。稍后我将为您提供更多相关信息。一般来说,您会尝试避免使用 KeyListener,因为这被认为是低级别的构造,并且对于此类事情来说可能太低,并且通常首选键绑定(bind)(根据键绑定(bind)教程)。

<小时/>

编辑 1
给你:How to use Key Bindings

直接引用 Swing 教程:

An alternative to key bindings is using key listeners. Key listeners have their place as a low-level interface to keyboard input, but for responding to individual keys key bindings are more appropriate and tend to result in more easily maintained code. Key listeners are also difficult if the key binding is to be active when the component doesn't have focus. Some of the advantages of key bindings are they're somewhat self documenting, take the containment hierarchy into account, encourage reusable chunks of code (Action objects), and allow actions to be easily removed, customized, or shared. Also, they make it easy to change the key to which an action is bound. Another advantage of Actions is that they have an enabled state which provides an easy way to disable the action without having to track which component it is attached to.


编辑2
请注意,有时您需要过滤输入到组件中的文本,并且需要使用DocumentFilter。我认为您当前的问题在某种程度上阻碍了我们,因为您尚未告诉我们此功能的总体目标是什么。请告诉我们更多信息,以便我们给您更好、更完整、更正确的答案。

关于java - 如何使 Swing JTextArea 响应 KeyEvents?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12923058/

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