【问题标题】:jComboBox editor returns empty StringjComboBox 编辑器返回空字符串
【发布时间】:2013-02-04 14:41:28
【问题描述】:

我编写了一个自动完成组合框程序,在该程序中搜索用户在文件中输入的单词。该程序运行良好,但是,combobox editor 在输入内容时不会返回任何内容。我不知道这是为什么.. 这是处理问题的代码块。

// in GUI class constructor
    InstantSearchBox = new JComboBox();
    InstantSearchBox.setEditable(true);

    /*****/
    KeyHandler handle = new KeyHandler();

    InstantSearchBox.getEditor().getEditorComponent().addKeyListener(handle);


// Keylistener class (KeyPressed method)
try
{
    dataTobeSearched = InstantSearchBox.getEditor ().getItem ().toString ();

    // the string variable is empty for some reason
    System.out.println ("Data to be searched " + dataTobeSearched); 
}
catch (NullPointerException e)
{
    e.printStackTrace ();
}

问候

【问题讨论】:

  • 我怀疑这种方式是否有可能提出一些建议......为了更好的帮助,尽快发布SSCCE,短可运行,可编译,大约JFrameJComboBox并带有Items的硬编码值
  • 这里有两个答案,不是,从来没有,这种方式不可能在Editor vs. 中捕获non_finalized KeyEvents。在 Swing 中为 Autocompleted funcionalities 铺设 Document

标签: java string swing jcombobox


【解决方案1】:

不要使用 KeyListener。生成 keyPressed 事件时,输入的文本尚未添加到文本字段中。

检查文本字段更改的更好方法是将 DocumentListener 添加到文本字段的 Document 中。有关详细信息,请参阅 How to Write a Document Listener 上的 Swing 教程部分。

【讨论】:

    【解决方案2】:

    你应该使用

    dataTobeSearched = (String) InstantSearchBox.getSelectedItem();
    尽管它的名字,对于可编辑的组合框,这个方法只返回输入的文本。

    编辑器仅由 JComboBox 在内部使用,以在输入时临时捕获输入。一旦他们键入,编辑器就会被清除,文本会被传输回组合框模型。

    这允许编辑器一次在多个组合框之间共享 - 他们只是在需要时跳入,捕获输入,再次跳出并在编辑完成时清除。

    【讨论】:

    • 我怀疑您是否误解了我,或者我无法理解您的观点。实际上,组合框的工作原理很像谷歌搜索框,用户在其中输入,并根据输入的内容是否完整,即时搜索在弹出框中提供建议。我正在尝试实现这一点
    【解决方案3】:

    使用InstantSearchBox.getSelectedItem() 代替InstantSearchBox.getEditor().getItem()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-13
      • 2013-06-09
      • 1970-01-01
      • 1970-01-01
      • 2020-01-27
      • 2020-07-11
      相关资源
      最近更新 更多