Java JTextArea KeyListener

PETI258 picture PETI258 · Aug 28, 2013 · Viewed 14.5k times · Source

When I pressed the ENTER my JTextArea starts a new row and I only want do to the doClick() method nothing else. How should I do that?

textarea.addKeyListener(new KeyListener(){
    @Override
    public void keyPressed(KeyEvent e){
        if(e.getKeyCode() == KeyEvent.VK_ENTER){
        button.doClick();
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }
});

Answer

Kevin Bowersox picture Kevin Bowersox · Aug 28, 2013

Use .consume():

Consumes this event so that it will not be processed in the default manner by the source which originated it.

public void keyPressed(KeyEvent e){
    if(e.getKeyCode() == KeyEvent.VK_ENTER){
    e.consume();
    button.doClick();
    }
}

Documentation