1

我试图忽略 JavaTextField 中的某些按键。我添加了一个 KeyListener,因为每次输入字母/数字/符号时我都需要触发一个事件。

我不希望在按下任何其他按钮时触发事件。为了实现这一点,我目前正在这样做:

        @Override
        public void keyPressed(KeyEvent arg0) {
            // System.out.println(arg0);
            if (arg0.getKeyCode() != (KeyEvent.VK_ENTER)
                    && arg0.getKeyCode() != (KeyEvent.VK_BACK_SPACE)
                    && arg0.getKeyCode() != (KeyEvent.VK_DELETE)
                    && arg0.getKeyCode() != (KeyEvent.VK_UP)
                    && arg0.getKeyCode() != (KeyEvent.VK_DOWN)
                    && arg0.getKeyCode() != (KeyEvent.VK_LEFT)
                    && arg0.getKeyCode() != (KeyEvent.VK_RIGHT)
                    && arg0.getKeyCode() != (KeyEvent.VK_SHIFT)
                    && arg0.getKeyCode() != (KeyEvent.VK_CAPS_LOCK)
                    && arg0.getKeyCode() != (KeyEvent.VK_PAGE_DOWN)
                    && arg0.getKeyCode() != (KeyEvent.VK_PAGE_UP)
                    && arg0.getKeyCode() != (KeyEvent.VK_SCROLL_LOCK)
                    && arg0.getKeyCode() != (KeyEvent.VK_NUM_LOCK)
                    && arg0.getKeyCode() != (KeyEvent.VK_ESCAPE)) {
                // fire event here
            }

        }

显然这是丑陋的。有什么更好的方法来做到这一点?

4

2 回答 2

2

单程

private static final List<Integer> ACCEPTED_KEYS = Arrays.asList(KeyEvent.VK_ENTER, ...);

public void keyPressed(KeyEvent event) {
  if (ACCEPTED_KEYS.contains(event.getKeyCode())
    // do something
}
于 2012-08-13T18:10:01.903 回答
1

您可以使用某种集合。某种类型的集合可能具有最快的查找速度。

// new class member
Set<Integer> ignoredKeyCodes = new HashSet<Integer>();

// add to class constructor
ignoredKeyCodes.add(KeyEvent.VK_ENTER);
// add other key codes

// check with
if (!ignoredKeyCodes.contains(arg0.getKeyCode())) // fire event here
于 2012-08-13T18:11:56.787 回答