描述
這個java.util.Observable.notifyObservers(Object arg)如果此對象已更改,則方法通知其所有觀察者,然後調用 clearChanged 方法以指示此對象已不再更改。
聲明
以下是聲明java.util.Observable.notifyObservers()方法
public void notifyObservers(Object arg)
參數
arg─ 任何物體。
返回值
NA
異常
NA
示例
下麵的例子展示了 java.util.Observable.notifyObservers(Object) 方法的用法。
package com.tutorialspoint;
import java.util.Observable;
import java.util.Observer;
class ObservedObject extends Observable {
private String watchedValue;
public ObservedObject(String value) {
watchedValue = value;
}
public void setValue(String value) {
// if value has changed notify observers
if(!watchedValue.equals(value)) {
System.out.println("Value changed to new value:"+value);
watchedValue = value;
// mark as value changed
setChanged();
// trigger notification with arguments
notifyObservers(value);
}
}
}
public class ObservableDemo implements Observer {
public String name;
public ObservableDemo(String name) {
this.name = name;
}
public static void main(String[] args) {
// create watched and watcher objects
ObservedObject watched = new ObservedObject("Original Value");
// watcher object listens to object change
ObservableDemo watcher = new ObservableDemo("Watcher");
// add observer to the watched object
watched.addObserver(watcher);
// trigger value change
watched.setValue("New Value");
}
public void update(Observable obj, Object arg) {
System.out.println(name+" called with Arguments:"+arg);
}
}
讓我們編譯並運行上麵的程序,這將產生以下結果——
Value changed to new value:New Value Watcher called with Arguments:New Value
相關用法
- Java Java.util.Observable.deleteObservers()用法及代碼示例
- Java Java.util.Observable.hasChanged()用法及代碼示例
- Java Java.util.Observable.countObservers()用法及代碼示例
- Java Java.util.Observable.addObserver()用法及代碼示例
- Java Java.util.Observable.clearChanged()用法及代碼示例
- Java Java.util.Observable.setChanged()用法及代碼示例
- Java Java.util.Observable.deleteObserver()用法及代碼示例
- Java Java.util.Calendar.setTimeInMillis()用法及代碼示例
- Java Java.util.BitSet.andNot()用法及代碼示例
- Java Java.util.Calendar.getMinimum()用法及代碼示例
- Java Java.util.GregorianCalendar.isLeapYear()用法及代碼示例
- Java Java.util.ResourceBundle.Control.getControl()用法及代碼示例
- Java Java.util.ArrayList.remove()用法及代碼示例
- Java Java.util.ArrayList.size()用法及代碼示例
- Java Java.util.Dictionary.remove()用法及代碼示例
- Java Java.util.Currency.getInstance()用法及代碼示例
- Java Java.util.ListResourceBundle.handleKeySet()用法及代碼示例
- Java Java.util.ResourceBundle.getBundle()用法及代碼示例
- Java Java.util.ArrayDeque.pop()用法及代碼示例
- Java Java.util.ServiceLoader.load()用法及代碼示例
注:本文由純淨天空篩選整理自 Java.util.Observable.notifyObservers() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。