我有一个问题,方法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);
            }
        }
    }

}

最佳答案

为了监听否决变更事件,您需要添加一个监听器。仅将方法放入JavaBean中是行不通的。要使其工作,您可以创建一个侦听器类:

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


然后在其他位置将侦听器添加到您的bean:

test.addVetoableChangeListener(new MyVetoableChangeListener());


或者您可以使用内部类来简化:

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

10-04 18:27