我对此代码有疑问:
CaptachaKey.addKeyListener(new KeyAdapter()
{
public void KeyPressed(KeyEvent e)
{
System.out.println("It works!" + e.getKeyCode());
if (e.getKeyCode() == 10)
{
text = CaptachaKey.getText();
f.setVisible(false);
}
}
});
它不起作用...... 如何在同一个类中添加此侦听器?
答案 0 :(得分:2)
而不是使用KeyListener
使用KeyBindings,例如代码10:
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("ENTER"), "doSomething");
getActionMap().put("doSomething",new AbstractAction() {
@Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("profit");
}
});
根据你的代码:
CaptachaKey.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("ENTER"), "doSomething");
CaptachaKey.getActionMap().put("doSomething",new AbstractAction() {
@Override
public void actionPerformed(ActionEvent arg0) {
text = CaptachaKey.getText();
f.setVisible(false);
}
});
当您按ENTER
键时,您的代码将被执行。