Java Programming
Keyboarding
Computer Keyboards

How do you write a working key listener in java that responds to an 'enter'?

User Avatar
Wiki User
2009-01-18 20:08:40

Almost all controls' ActionListener triggers the actionPerformed

upon the enter key press == == Using an anonymous class

implementation:

Component c; // this is the component you want to add a listener

to

c.addKeyListener(new KeyListener() {

public void keyPressed(KeyEvent e) {

if(e.getKeyChar() == e.VK_ENTER) {

// put the code you want to execute when Enter is pressed

here

System.out.println("ENTER PRESSED");

}

}

// unused abstract methods

public void keyTyped(KeyEvent e) {}

public void keyReleased(KeyEvent e) {}

});


Copyright © 2020 Multiply Media, LLC. All Rights Reserved. The material on this site can not be reproduced, distributed, transmitted, cached or otherwise used, except with prior written permission of Multiply.