Java KeyEvent &语法高亮

发布于 2024-10-02 07:55:19 字数 463 浏览 6 评论 0原文

我正在用 Java 编写一个语法突出显示文本编辑器,但我遇到了一些问题,即我应该做什么而不是我想要做什么。基本上,KeyEvent 类给我带来了一些问题:

  1. KeyTyped 不允许我 ID 关键是什么所以它没用 乐行。
  2. KeyPressed 更好,它允许我 按下时识别每个键 然而,这对于词法分析来说非常有用 它在按键之前触发事件 实际上被放入 JEdi​​torPane。
  3. KeyReleased 解决了以下问题 KeyPressed 和键键入为它 发生在角色被选中之后 输入,它让我实际上 ID 是什么字符。然而如果 我按住“a”,它会输入 50 个“a”, 我完蛋了。

我解决这个问题的方法是对所有要输入的字符使用 KeyPressed,使用事件,读取应该输入的字符并手动输入它,但是我猜这不是最优雅的解决方案。我的问题是我还能怎么做呢?有什么东西我只是忽略了,还是我找到了问题的解决方案并且应该顺其自然?

I'm writing a syntax highlighting text editor in Java and I've run into a bit of a problem as to what I should do as opposed to what I want to do. Basically the KeyEvent class provides me with a bit of a problem:

  1. KeyTyped does not allow me to ID
    what the key is so it is useless for
    lexing.
  2. KeyPressed is better, it allows me
    to ID each key as it is pressed
    which is great for lexing, however
    it triggers the event before the key
    is actually put into the
    JEditorPane.
  3. KeyReleased solves the problem of
    both KeyPressed & KeyTyped as it
    occurs after the character has been
    input and it allows me to actually
    ID what the character is. However if
    I hold 'a' and it puts in 50 'a's,
    I'm screwed.

My solution to the issue is to use KeyPressed for all characters that are to be input, consume the event, read the character that was supposed to be input and manually input it, however I'm guessing this isn't the most elegant solution available. My question is how else could I go about this? Is there something I'm just glazing over or did I find the solution to my problem and should just roll with it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦初启 2024-10-09 07:55:19

JavaDoc 似乎相反您对 KeyEvent 的评价:

getKeyChar 方法始终返回一个
有效的 Unicode 字符或
CHAR_UNDEFINED。字符输入是
由 KEY_TYPED 事件报告:
KEY_PRESSED 和 KEY_RELEASED 事件
不一定与
字符输入。因此,结果
getKeyChar 方法的保证
仅对 KEY_TYPED 有意义
事件。

The JavaDoc appears to be the opposite of what you say for KeyEvent:

The getKeyChar method always returns a
valid Unicode character or
CHAR_UNDEFINED. Character input is
reported by KEY_TYPED events:
KEY_PRESSED and KEY_RELEASED events
are not necessarily associated with
character input. Therefore, the result
of the getKeyChar method is guaranteed
to be meaningful only for KEY_TYPED
events.

比忠 2024-10-09 07:55:19

您可能应该使用文档侦听器

You should probably be using a Document Listener.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文