What is the difference of use between Keypressed and Actionperformed?

Asked

Viewed 1,128 times

19

I ran some tests to see the difference in use, and apparently they both go off under pressure 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:

inserir a descrição da imagem aqui

Therefore, I would like to leave the following questions:

  • Is there any difference between using actionPerformed or keyPressed, for example in a text box?
  • There are differences in the way they both perform?

2 answers

7


General difference:

The 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 message button "Action Triggered." will be shown.

Keylistener is used to handle key-related events (more specific than Actionperformed).

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

In your case, where you will 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 releasing the key pressed:

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 that with a Actionlistener.

There are differences in the way they both perform ?

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

  • 1

    Good answer! :)

6

Keypressed is a keylistener interface method inherited from Eventlistener. Actionperformed is an interface method ActionListener, which takes as a parameter the ACTIONEVENT, which also inherits from Eventlistener. We have to analyze that both methods recover events, but Actionperformed is more generic, being triggered with the occurrence of any type of event in the application.

When analyzing in the documentation it is explained that the parameter that Actionperformed receives ,AN ACTIONEVENT, HAS A DEFAULT VALUE that is the space bar running an Actionevent on a button.

The documentation says so:

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

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 Processing details of individual mouse movements and clicks and can process a "significant" (semantic) event such as "button pressed".

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 parameter that is in note of the explanation of the documentation.

The keypressed will be able to manipulate keyboard inputs having several options for you to be more specific in the programming of keyboard events.

I think this is based on the documentation

  • 1

    It is always interesting to translate mentions in English, :)

  • ah blz, I translated the text of the documentation in the translator, I think that attrition became legible what found?

  • From one formatted in this answer, you are very confused, and now with the translation, can not know where begins and ends the quote you translated.

  • He was really confused,

  • In a text field is not the space bar that triggers Action, it is the enter button. I think the explanation slipped a little from the question, and even failed to answer the first question. By the way, reading only your answer, I think that neither of the two questions is answered, at least it was not clear to me.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.