如何调用vetoableChange?

时间:2014-10-06 22:58:34

标签: java

我遇到一个问题,方法fireVetoableChange()未调用vetoableChange() 有我的代码的例子。

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);
            }
        }
    }

}

1 个答案:

答案 0 :(得分:2)

要收听可撤销的更改事件,您需要添加一个侦听器。只是将方法放在JavaBean中是行不通的。要使其工作,您可以创建一个监听器类:

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

然后在其他地方添加一个监听器:

test.addVetoableChangeListener(new MyVetoableChangeListener());

或者你可以通过内部课程来缩短时间:

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