Aero
Aero

Reputation: 19

How to call vetoableChange?

I have one problem, method fireVetoableChange() didn't call vetoableChange()
There is example of my code.

import java.beans.PropertyChangeEvent;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
import java.beans.VetoableChangeSupport;

import javax.swing.JOptionPane;

public class TestVetoable {
    private int x;
    private final VetoableChangeSupport vcs;

    public TestVetoable(){
        vcs = new VetoableChangeSupport(this);
    }

    public void addVetoableChangeListener(VetoableChangeListener listener) {
             vcs.addVetoableChangeListener(listener);
    }

    public void removeVetoableChangeListener(VetoableChangeListener listener) {
             vcs.removeVetoableChangeListener(listener);
    }

    public int getX(){
        return x;
    }

    public void setX(int newX){
        try{
            vcs.fireVetoableChange("x", x, newX);
        }
        catch (PropertyVetoException e){
            JOptionPane.showMessageDialog(null, "Some phrase");
        }
        x = newX;
    }

    public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException {
        if (evt.getPropertyName().equals("x")){
            if ((Integer) evt.getOldValue() > (Integer) evt.getNewValue()){
                throw new PropertyVetoException("Again some phrase", evt);
            }
        }
    }

}

Upvotes: 0

Views: 1310

Answers (1)

tbodt
tbodt

Reputation: 17007

In order to listen to vetoable change events, you need to add a listener. Just putting the method in your JavaBean won't work. To make it work, you can create a listener class:

public class MyVetoableChangeListener {
    public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException {
        // do something
    }
}

And then add a listener to your bean somewhere else:

test.addVetoableChangeListener(new MyVetoableChangeListener());

Or you can shorten things up with an inner class:

test.addVetoableChangeListener(new VetoableChangeListener() {
    @Override
    public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException {
        // do something
    }
});

Upvotes: 2

Related Questions