我试图忽略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
}
}
显然这很难看。有什么更好的方法呢?
答案 0 :(得分: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
}
答案 1 :(得分: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