gpt4 book ai didi

java - 无法用JavaBeans制作程序来监听其他组件

转载 作者:行者123 更新时间:2023-11-30 06:41:44 24 4
gpt4 key购买 nike

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

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

有什么想法吗?

最佳答案

你的输出是什么?

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

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

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

关于java - 无法用JavaBeans制作程序来监听其他组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44286039/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com