javaeventsevent-handlingpropertychangelistener

PropertyChangeListener Java


I'm currently learning to use the PropertyChangeListener and PropertyChangeSupport class. I'm a bit stuck in the part where the listener receives the event so I'll need some help with this part.

In my program there are 2 classes:

Controller:

    public class Controlador implements PropertyChangeListener {
        private ControlAccesos modelo;
        private GUIpanel vistaPan;
        private GUIsenal vistaSen;


     public Controlador(GUIpanel vista1, GUIsenal vista2, ControlAccesos model){

        modelo=model;
        vistaPan = vista1;
        vistaSen = vista2;

        modelo.addPropertyChangeListener(this);

     }


     public void propertyChange(PropertyChangeEvent evt) {
        System.out.print("Resultado");
        if (evt.getPropertyName().equals("mensaje")){
            vistaPan.refrescaMensaje((String)evt.getNewValue());
        }

     }
}

Model:

/**
 * Clase principal del sistema de control de accesos a la facultad.
 */
public class ControlAccesos
{

    /**
     * Mesaje shown in the GUI
     */
    private String mensaje;
    private PropertyChangeSupport changeSupport = new PropertyChangeSupport(this);
     .
     .
     .
    public void TarjetaDetectada( String usuario )
    {
        state.TarjetaDetectada(this, usuario);
        changeSupport.firePropertyChange("mensaje",this.mensaje,this.mensaje);
    }

    public void addPropertyChangeListener( PropertyChangeListener listener ){

        changeSupport.addPropertyChangeListener(listener);
    }

The problem is that the code never reaches the propertyChange function ("Resultado" is never printed on the screen).

Thank you in advance.


Solution

  • From the documentation for PropertyChangeSupport.firePropertyChange: “No event is fired if old and new values are equal and non-null.” This makes sense, since there is no reason to fire an event if the value has not actually changed.

    Bean properties are represented by get-methods (or, if a property’s type is a primitive boolean, an is-method). Writable properties also have a corresponding set-method. Normally, you would call firePropertyChange from such a set-method, in which case you would have both an old value and a new value:

    public String getMensaje() {
        return mensaje;
    }
    
    public void setMensaje(String mensaje) {
        String old = this.mensaje;
        this.mensaje = mensaje;
        changeSupport.firePropertyChange("mensaje", old, this.mensaje);
    }