【问题标题】:Can not make program with JavaBeans to listen to other components不能用 JavaBeans 制作程序来监听其他组件
【发布时间】:2017-05-31 13:23:20
【问题描述】:
import java.beans.PropertyVetoException;

public class Main {
  public static void main(String[] args) {

    Purchase purch = new Purchase("Computer");

    PurchaseView pView = new PurchaseView();
    purch.addPropertyChangeListener(pView);

    try {
      purch.setData("Notebook");
      System.out.println(purch);

    } catch (PropertyVetoException exc) {
      System.out.println(exc.getMessage());
    }

  }
}

你有 Purchase 和 PurchaseView 类:

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.beans.PropertyVetoException;

public class Purchase {

    private String data;

    private PropertyChangeSupport propertyChange = new PropertyChangeSupport(this);

    public Purchase(String data) {
        this.data = data;
    }

    public synchronized void addPropertyChangeListener(PropertyChangeListener listener) {
        propertyChange.addPropertyChangeListener(listener);
    }

    public synchronized void removePropertyChangeListener(PropertyChangeListener l) {
        propertyChange.removePropertyChangeListener(l);
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        String oldValue = data;
        this.data = data;
        propertyChange.firePropertyChange("data", oldValue, data);
    }
    }
}  


import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

public class PurchaseView implements PropertyChangeListener{

    public PurchaseView() {}

    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        String propName = evt.getPropertyName();
        if(propName.equals("data")) {
            String oldValue = (String) evt.getOldValue();
            String newValue = (String) evt.getNewValue();
            System.out.println("Change value of: " + evt.getPropertyName() + " from: " + oldValue + " to: " + newValue);
        }
    }
}

我希望程序在数据属性更改时产生输出,如 PurchaseView 类中所示。对我来说似乎实现得很好,但它不起作用。

有什么想法吗?

【问题讨论】:

    标签: java javabeans


    【解决方案1】:

    你的输出是什么?

    我认为你在 setData 方法中使用 oldValue 时犯了一个错误。应该是这样的:

    public void setData(String data) {
        String oldValue = this.data;
        this.data = data;
        propertyChange.firePropertyChange("data", oldValue, data);
    }
    

    请注意,您忘记了 setData 方法第一行的this 保留字,这意味着您使用方法变量而不是类变量。

    【讨论】:

    • 我没有任何输出。我实际上解决了这个问题。它与变量命名有关。我区分 data 和 this.data 但我的程序没有。我有类似你的解决方案,但它没有用。我将方法参数的名称从 'data' 更改为 'aData' 并且 firePropertyChange 传递了 'aData' 变量并且它工作正常。
    猜你喜欢
    • 2019-06-11
    • 2018-11-23
    • 2017-03-17
    • 1970-01-01
    • 2018-06-11
    • 2018-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多