Java JTextArea KeyListener

15,168

Solution 1

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

Solution 2

You should use KeyBindings with any JTextComponent in question. KeyListeners are way too low level from Swing's perspective. You are using the concept which was related to AWT, Swing uses KeyBindings to do the same task with more efficiency and provides desired results :-)

A small program for your help :

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class KeyBindingExample {

    private static final String key = "ENTER";
    private KeyStroke keyStroke;

    private JButton button;
    private JTextArea textArea;

    private Action wrapper = new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            button.doClick();
        }
    };

    private void displayGUI() {
        JFrame frame = new JFrame("Key Binding Example");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        JPanel contentPane = new JPanel(new BorderLayout(5, 5));

        textArea = new JTextArea(10, 10);
        keyStroke = KeyStroke.getKeyStroke(key);
        Object actionKey = textArea.getInputMap(
                JComponent.WHEN_FOCUSED).get(keyStroke);
        textArea.getActionMap().put(actionKey, wrapper);

        button = new JButton("Click Me!");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                System.out.format("Button Clicked :-)%n");
            }
        });     

        contentPane.add(textArea, BorderLayout.CENTER);
        contentPane.add(button, BorderLayout.PAGE_END);

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                new KeyBindingExample().displayGUI();
            }
        };
        EventQueue.invokeLater(r);
    }
}
Share:
15,168
PETI258
Author by

PETI258

Updated on July 16, 2022

Comments

  • PETI258
    PETI258 almost 2 years

    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) {
        }
    });
    
  • Kevin Bowersox
    Kevin Bowersox over 10 years
    @PéterSzakács Excellent! Glad I could help.
  • camickr
    camickr over 10 years
    Don't use a Key Listener. Swing was designed to be used with Key Bindings.