SwingPropertyChangeSupport 實作
要實作SwingPropertyChangeSupport 並觀察應用程式中的屬性變化,您可以參考以下範例:
🎜>
<code class="java">import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.event.SwingPropertyChangeSupport; public class MyObservableClass { private SwingPropertyChangeSupport propertyChangeSupport = new SwingPropertyChangeSupport(this); private String name; // A property we want to observe public void setName(String newName) { String oldValue = this.name; this.name = newName; propertyChangeSupport.firePropertyChange("name", oldValue, newName); } public String getName() { return name; } public void addPropertyChangeListener(PropertyChangeListener listener) { propertyChangeSupport.addPropertyChangeListener(listener); } public void removePropertyChangeListener(PropertyChangeListener listener) { propertyChangeSupport.removePropertyChangeListener(listener); } } // Example Usage MyObservableClass observableClass = new MyObservableClass(); PropertyChangeListener listener = new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals("name")) { System.out.println("Name changed to: " + evt.getNewValue()); } } }; observableClass.addPropertyChangeListener(listener); observableClass.setName("New Name"); // This will trigger the listener</code>
以上是如何實作SwingPropertyChangeSupport進行屬性變化觀察?的詳細內容。更多資訊請關注PHP中文網其他相關文章!