What is the difference of use between KeyPressed and ActionPerformed?

18

I made tests to see the difference in use, and apparently both of them fire by pressing ENTER on the keyboard, as can be seen in the example below:

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

public class KeyListenerActionPerformTest extends JFrame {

    private JPanel contentPane;
    private JPanel panel;
    private JTextField textField;
    private JPanel panel2;
    private JScrollPane scrollPane;
    private JTextArea textArea;

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            KeyListenerActionPerformTest frame = new KeyListenerActionPerformTest();
            frame.setVisible(true);
        });
    }

    public KeyListenerActionPerformTest() {
        initComponents();
    }

    private void initComponents() {

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.contentPane = (JPanel) getContentPane();

        this.panel = new JPanel();
        this.panel.setBorder(new TitledBorder("Campo c/ Action e KeyListener"));
        this.contentPane.add(this.panel, BorderLayout.CENTER);

        this.textField = new JTextField(10);

        this.textField.addActionListener(e -> {
            textArea.append("Action triggered.\n");
        });

        this.textField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                textArea.append("KeyEvent triggered.\n");
            }
        });

        this.panel.add(this.textField);

        this.panel2 = new JPanel();
        getContentPane().add(this.panel2, BorderLayout.SOUTH);

        this.textArea = new JTextArea(5, 15);
        this.textArea.setLineWrap(true);
        this.scrollPane = new JScrollPane(textArea);
        this.panel2.add(this.scrollPane);

        pack();
        setLocationRelativeTo(null);
    }
}

And running by pressing enter:

Faced with this, I would like to leave the following questions:

  • Is there any difference between using actionPerformed or keyPressed , for example, in a text field?
  • Are there differences in how they both perform?
asked by anonymous 30.08.2017 / 16:01

2 answers

7
  

Difference in general:

ActionPerformed is used to handle any event that a user can perform. Examples: Click a button, select a menu item, or press enter on a text field .

So, for example, if you add the following code in JFrame :

JButton testeAction = new JButton("Action");
testeAction.addActionListener(e -> {
    textArea.append("Action triggered.\n");
});
testeAction.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            textArea.append("KeyEvent triggered.\n");
        }
});
this.panel.add(testeAction);

You will see that every time a user clicks the button " Action triggered. " is displayed.

KeyListener is used to handle events related to keys (More specific than ActionPerformed).

  

Is there any difference between using actionPerformed or KeyListener, for example, in a text field?

In your case, where you only need to handle the keystroke event, there is no difference. However, imagine a situation where you have an action for the event of pressing the key and another action when you release the key:

this.textField.addKeyListener(new KeyAdapter() {
    @Override
    public void keyReleased(KeyEvent e) {
        textArea.append("KeyReleased triggered.\n");
    }
});

this.textField.addKeyListener(new KeyAdapter() {
    @Override
    public void keyPressed(KeyEvent e) {
        textArea.append("KeyPressed triggered.\n");
    }
});

It would be harder to do this with an ActionListener .

  

Are there differences in how they both perform?

Both are listeners (through the EventListener interface). There is no difference in execution between the two.

    
17.09.2017 / 00:54
6

Keypressed is a method of the keylistener interface that inherits from Eventlistener. Actionperformed is a method of the ActionListener interface, which is parameterized by ACTIONEVENT, which also inherits from EventListener. We have to analyze that both methods retrieve events, however Actionperformed is more generic, being triggered by the occurrence of any type of event in the application.

When we look at the documentation it is explained that the parameter that Actionperformed receives, a ACTIONEVENT, has a DEFAULT value that is the spacebar running an ActionEvent on a button.

The documentation says this:

  

A semantic event that indicates that an action has been defined by the   component. This high-level event is generated by a component (such as   button) when the specific action of the component occurs (such as   pressed). The event is passed to each ActionListener object that   you registered to receive these events using method   component addActionListener.

     

Note: To invoke an ActionEvent on a button using the keyboard, use the   spacebar.

     

The object that implements the ActionListener interface gets this   ActionEvent when the event occurs. The listener is therefore spared the   details of processing individual mouse movements and clicks   mouse, and can process a "significant" (semantic) event as   "pressed" button.

     

An unspecified behavior will be caused if the id parameter of   any specific ActionEvent instance is not in the range of   ACTION_FIRST for ACTION_LAST.

If you do not specify the parameters it will receive default action as the parameter that is in the note of the documentation explanation.

The keypressed will allow you to manipulate keyboard inputs having several options so you can be more specific in programming keyboard events.

I think this is based on documentation

    
01.09.2017 / 18:21