我试图忽略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
}
}
显然这很丑。有什么更好的方法可以做到这一点?
最佳答案
单程
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
}
关于java - 优雅地忽略按键,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11939804/