【问题标题】:What is the difference between adding a KeyListener to JCombobox editor and JCombobox itself将 KeyListener 添加到 JCombobox 编辑器和 JCombobox 本身有什么区别
【发布时间】:2015-05-02 17:59:03
【问题描述】:
    listItemsCombo.getEditor().getEditorComponent().addKeyListener(new keyPressListener()); //Works correct

这很好用。但是,在将 keyListener 添加到 jcomboBox 时,keyPress 在按“Enter”时不会被识别。向 jComboxBox 添加 keyListener 和向其编辑器添加侦听器之间的确切区别是什么?何时向编辑器添加侦听器?

   listItemsCombo.addKeyListener(new KeyPressListener())//When should we use this?

【问题讨论】:

标签: java swing


【解决方案1】:

向 jComboxBox 添加 keyListener 和向其编辑器添加监听器之间的确切区别是什么?

KeyEvents 只分派给有焦点的组件。

何时将监听器添加到编辑器?

您不应在组合框或编辑器上使用 KeyListener。 Swing 旨在与Key Bindings 一起使用。使用 Key Bindings,即使组件没有焦点(如果您愿意),您也可以处理 KeyStroke。阅读 How to Use Key Bindings 上的 Swing 教程部分了解更多信息。

【讨论】:

  • 可以使用KeyBindings。我也需要听 KeyTyped。 KeyBindings 可用于 KeyPress。但是为了从 keyBoard 获取 userInput(像 abc .. 这样的键),我需要添加一个 keyListener 对吗?或者它可以使用 keyBindings 来执行?
  • @divya,当您想在按下特定键时调用操作时使用键绑定。如果您只想知道文本何时添加到文本字段,那么您应该使用DocumentListener。本教程还有一个关于“如何编写 DocumentListener”的部分。
猜你喜欢
  • 2015-01-23
  • 1970-01-01
  • 1970-01-01
  • 2012-12-12
  • 2010-11-16
  • 1970-01-01
  • 1970-01-01
  • 2010-12-19
  • 1970-01-01
相关资源
最近更新 更多