What is and how to implement a Java Listener?

Asked

Viewed 6,600 times

12

  • 2

    On Android Listener uses a lot, and I still get confused about this, whether it’s something restricted from Java or some kind of pattern that can be implemented in other languages. Anyway, the question is very interesting, so follow my contribution +1

  • 2

    Downvote, in addition to negative, why don’t you contribute to the question by citing what can be improved on it?

  • Do you want to implement Listener for something of your own, or do you want to implement something existing? I think Listener refers to the events of an object, where the object can receive multiple events of the same type, so thinking of something simple, you would have to have the event logger in the interface of the "class" and a Rigger for each type of event, the action/Trigger happens as and when you wish, for example if the object is "destroyed" there could be events to get it, or if you change a variable of the object you would emit a "Trigger".

  • @Guilhermenascimento wanted to know how I implement a Istener, what it takes for me to create it.

  • @Articuno can I send you a pseudo-code? I’m kind of out of practice to answer and xD patience

  • @Guilhermenascimento without problems :) what I wanted is to understand the concept in practice, I put java to question not fall too wide.

  • Analogically, the listener serves as sight, hearing, touch, smell, and taste. For each action, a reaction (of course if you create a schedule for this). It smelled a coffee, go straight to the kitchen to get. hehe

  • 1

    @Articuno this is not a java example or https://pastebin.com/BjthmL51, in java there are classes that help in this, the idea is just to explain to you in a simple code the idea. I created two types of events baz and bar, in case the bar is specifically triggered when it executes changeFoobar(), if you need to know when the task that takes care of the changeFoobar() execute it to inform another task, you can register an event called obj.on("bar", function () { ... });...

  • 1

    ... can actually record several events obj.on("bar", function () { ...informa ao joão que alterou o status... });, can actually record several events obj.on("bar", function () { ...informa a maria que alterou o status... });, This is all as I said, a pseudo-code to exemplify, there are classes in java that easily implement listeners to an object. As soon as possible, if no one provides you with an example I will venture one, it is that I do not have as much skill with this language.

  • @Guilhermenascimento what that would be push?

  • @Articuno is the one that adds a Function to the specified array, where the Baz or bar events will be recorded

Show 6 more comments

2 answers

11


The Observer Standard goes far beyond Java and Swing

As you have seen, "Listener" and "Observer" are different names for the same pattern, and, it can be used for many things other than use in Swing, and can be implemented in many other languages. Within Java, for example, the Javafx bindings system uses (internally) the Observer standard when binding between Properties, which allows one Property to be changed (updated) when another is; and this system can be used even in software without a Graphical Interface (you can enjoy the Properties and bindings even without a GUI).

Why use the Observer Standard

It is common to use this pattern when you want a certain code to be executed (the observer’s code) when a certain thing happens (the event) in something (this "something" is the observed thing, which can be for example, a Button on the Screen).

It is also common to use this standard to update data automatically (which is the case with Javafx Properties and Bindings); in this case, you may have an implementation that ensures even data coherence from these automatic updates.

  • For example, you may have an attribute dataDeNascimento and an attribute idade within an Object Pessoa, and, make it, when the value in dataDeNascimento is changed, the value in idade be it automatically updated, in order to ensure that the idade at all times will correspond correctly to the date of birth. So, if you call setDataDeNascimento(...) and then callgetIdade() will get the age already updated (but be careful with competition problems, not to read data not yet updated or, in the case of long data structures being updated, do not end up reading the structure while it is still "updated by half").

Example of using the Observer Standard

The Code below is a simple implementation to exemplify the Observer Standard:

public class Observado {
    private Object atributoQualquer;
    private final List<Observador> observadores = new ArrayList<Observador>();

    private void notificarObservadores() {
        for (Observador observador : observadores) {
            observador.notificar(this);
        }
    }
    public void adicionarObservador(Observador obs) { //também chamado de addListener(...)
        observadores.add(obs); //"obs" passará a ser notificado sobre mudanças em this
    }
    public void removerObservador(Observador obs) { //também chamado de removeListener(...)
        observadores.remove(obs); //"obs" deixará de ser notificado sobre mudanças em this
    }
    public void setAtributoQualquer(Object novoValor) {
        atributoQualquer = novoValor;
        notificarObservadores(); //avisamos os Observadores que houve uma alteração em this
    }
}

public interface Observador { //também chamado de "Listener"
    public void notificar(Observado obs); //também chamado de "notify()"
}

public class ObservadorA implements Observador {
    public void notificar(Observado obs) { //Chamado quando ocorrer uma alteração em "obs"
        //Atualiza dados, executa código que deve ser executado quando "obs" for alterado, etc.
        //Aqui dentro pode-se chamar GETTERS de "obs" para obter os novos dados em "obs", como chamar "obs.getAtributoQualquer()"
    }
}

Having the above code, it is still necessary to register the ObservadorA as an observer of Observado so that he can be notified when the Observado is changed, we can do it like this:

Observado observado = new Observado();
observado.adicionarObservador(new ObservadorA());

There, that way the method notificar(...) of ObservadorA() will be called when the observado is amended (modified by calling setAtributoQualquer(...)).

Considerations on this Example:

  • I made a method notificar(Observado obs), This method signature causes the Observer to "pull" (pull) the data of obs to be able to know what has changed and what are the new values in obs, this is done by calling the GETTERS obs.

  • The method could be, for example, notificar(Object novoValor) or notificar(Observado obs, Object novoValor)or notificar(Observado obs, Object novoValor, Object valorAnterior), any of these would be "pushing" (push) the data for the Observer, so he doesn’t have to call the Getters obs.
    Note: the signature notificar(Observado obs, Object novoValor, Object valorAnterior) is similar to the signature of the method changed(...) class ChangeListener javafx:
    void changed(ObservableValue<? extends T> observable, T oldValue, T newValue)

  • It is common for "Observed" to allow adding "Observers" to different types of events/changes, so you will find methods like addXXXXListener(), addYYYYListener(), etc. (for example, addFocusListener(...), addActionListener(...), addMouseListener(...), etc.). This allows you to create codes to "listen" (or "observe") different things, without having to listen/observe everything that happens in the Observed object.

  • It is also very common to create Anonymous Classes and more recently, Lambda expressions, instead of creating Observant Classes/Listeners, this reduces the amount of code, and is used directly in the methods addXXXXListener(...). Examples:

    • botao.addActionListener(new ActionListener() { //Classe Anônima @Override public void actionPerformed(ActionEvent e) { System.out.println("Clicado!"); } });

    • botao.addActionListener(e -> { System.out.println("Clicado!"); }); //Lambda

Javafx has an Observer system that is very interesting, and that goes far beyond what I presented here, I highly recommend study it.

  • 1

    Excellent answer! D

0

If we translate the word Listener into Portuguese we will have the word "Listener". Listener in Portuguese is defined as "He who hears".

And now on schedule?

We can define him as a listener too, why does he stay as if attentive to all user actions.

It is waiting, as if it were filtered all the data generated by the user (Moving the mouse, click the mouse, pressed key...), to then take the set attitude.

If we were to assign synonyms the Listener function would be assigned the following words:

  • Listener

  • Receiver

  • Spectator

  • Helper

  • Watcher

Perhaps due to the extent of the subject I recommend reading carefully the following subject that covers this well.

http://www.devmedia.com.br/javalisteners-trabalhando-com-actionlistener-e-keylistener-em-java/31850

Example of a listener interface:

public interface EventListener {
    void fireEvent (Event e);
}

A video that may also be of help for creation would be this: https://youtu.be/-ATbC-4rhc4

Listener possessed some peculiarity s that makes it difficult to explain by writing.

  • 3

    And an example of how to implement?

  • 1

    Can’t be a more simplified example right? This class is kind of hard to understand.

  • @Articuno It’s simpler now?

  • Until too much, I did not understand how to implement with this example. What I’d like to see is how I can create a Software from scratch, what I need to do to make it work properly.

  • @Articuno https://youtu.be/-ATbC-4rhc4 I believe this to be very illuminating, and it is in Portuguese:)

  • I’m going to turn this answer into a wiki, maybe make it easier to find a better explanation

  • 2

    The problem with the video is that it doesn’t add its answer. Imagine if someone falls for this question and doesn’t read comments, or if the video is deleted? The ideal is to have the explanation in the answer, it should be independent of external websites and links.

Show 2 more comments

Browser other questions tagged

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