Как добавить ключевой слушатель к JComboBox с AutoCompleteSupport (glazedlists) в Java SE - PullRequest
3 голосов
/ 18 ноября 2011

Как мне добавить KeyListener к JComboBox с помощью «AutoCompleteSupport» (glazedlists) в Java SE. Я работаю над небольшой программой, которая имеет JComboBox, которая работает с AutoCompleteSupport. Я хочу выполнить метод, если я нажму клавишу Enter в JComboBox. Как я могу сделать это с AutoCompleteSupport?

1 Ответ

2 голосов
/ 18 ноября 2011

Оформить AutoCompleteSupport (Glazed Lists) , в котором упоминается:

JComboBox ActionEvents

В JComboBox запускается одно событие ActionEvent в следующих ситуациях:

  1. пользователь нажимает клавишу ввода
  2. выбранный элемент во всплывающем окне изменяется (что может произойти из-за щелчка мыши, изменения термина автозаполнения или использования клавиш со стрелками)
  3. JComboBox теряет фокус и содержит значение, которое не отображается в ComboBoxModel

Также ознакомьтесь со следующими выдержками из источника:

public void keyPressed(KeyEvent e) {
    if (!isTableCellEditor)
        doNotTogglePopup = false;

    // this KeyHandler performs ALL processing of the ENTER key otherwise multiple
    // ActionEvents are fired to ActionListeners by the default JComboBox processing.
    // To control processing of the enter key, we set a flag to avoid changing the
    // editor's Document in any way, and also unregister the ActionListeners temporarily.
    if (e.getKeyChar() == KeyEvent.VK_ENTER) {
        doNotChangeDocument = true;
        this.actionListeners = unregisterAllActionListeners(comboBox);
    }

    // make sure this backspace key does not modify our comboBoxEditorComponent's Document
    if (isTrigger(e))
        doNotChangeDocument = true;
}

И

public void keyReleased(KeyEvent e) {
    // resume the ability to modify our comboBoxEditorComponent's Document
    if (isTrigger(e))
        doNotChangeDocument = false;

    // keyPressed(e) has disabled the JComboBox's normal processing of the enter key
    // so now it is time to perform our own processing. We reattach all ActionListeners
    // and simulate exactly ONE ActionEvent in the JComboBox and then reenable Document changes.
    if (e.getKeyChar() == KeyEvent.VK_ENTER) {
        updateFilter();

        // reregister all ActionListeners and then notify them due to the ENTER key

        // Note: We *must* check for a null ActionListener[]. The reason
        // is that it is possible to receive a keyReleased() callback
        // *without* a corresponding keyPressed() callback! It occurs
        // when focus is transferred away from the ComboBoxEditor and
        // then the ENTER key transfers focus back to the ComboBoxEditor.
        if (actionListeners != null) {
            registerAllActionListeners(comboBox, actionListeners);
            comboBox.actionPerformed(new ActionEvent(e.getSource(), e.getID(), null));
        }

        // null out our own reference to the ActionListeners
        actionListeners = null;

        // reenable Document changes once more
        doNotChangeDocument = false;
    }

    if (!isTableCellEditor)
        doNotTogglePopup = true;
}

Похоже, вы хотите ActionListener вместо KeyListener.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...