java - 如何使 Swing JTextArea 响应 KeyEvents?

标签 java swing jtextarea keyevent

我有一个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/

相关文章:

java - 在 Java 中,嵌套类与其外部类之间的关系是什么?

Java 7 - JPanel PaintComponent 标题栏重叠

java - JTextArea 与 String 之间的转换

java - 如何滚动我的屏幕

java - 如何将CSS类放入html :select element in jsp

java - 如何使用java从http url(视频流链接)下载视频文件?

java - addKeyListener() 不适用于 JPanel

java - 如何在 JPanel 类中添加热键 Enter?

java - 如何让 JTextArea 完全填满 JPanel?

java - JScrollPane 不在 MigLayout 中滚动