Hans
Hans

Reputation: 1582

JComboBox second KeyListener prevents first to get fired

I'm observing the following behaviour:

adding a new KeyListener to JComboBox and calling e.consume() stops the Default KeyListener from firing its Events.

Here is my example code:

final JComboBox cb = new JComboBox(fooList);

final KeyListener fooKeyListener = new KeyAdapter(){
  @Override
  public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_DOWN) {
      System.out.println("VK_DOWN fired");
      e.consume();
    }
  }
};

cb.addKeyListener(fooKeyListener);
contentPanel.add(cb);

After this, when I press the Arrow Down Button, I only get "VK_DOWN fired" outputted and the whole Scrolling/Selecting-Mechanism stops working.

I would expect, that the default KeyListener, which is responsible for all that scrolling-Stuff gets executed first, so e.consume() shouldn't stop it from working. And by the way, calling e.consume() is the only way to stop the Scrolling mechanism! Even calling cb.removeKeyListener(cb.getKeyListeners()[0]); does not stop the Scrolling mechanism from working (which, in my opinion, seems to be very weird!).

Any help appreciated!

Upvotes: 0

Views: 251

Answers (1)

camickr
camickr

Reputation: 324207

I would expect, that the default KeyListener, which is responsible for all that scrolling-Stuff gets executed first,

Actually the order of event firing is not defined and you should never code assuming a specific order. In fact the current default implementation invokes the last listener added first.

Even calling cb.removeKeyListener(cb.getKeyListeners()[0]); does not stop the Scrolling mechanism from working (which, in my opinion, seems to be very weird!).

Swing was designed to use Key Bindings. Scrolling is enabled by a default Action being mapped to the Down key. You can see all the default mappings by checking out Key Binding Defaults

calling e.consume() is the only way to stop the Scrolling mechanism!

You can disable the default Key Binding for the Down arrow by using:

InputMap im = comboBox.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
im.put(KeyStroke.getKeyStroke("DOWN"), "none");

Upvotes: 1

Related Questions