// This example is from the book Developing Java Beans by Robert Englander.
// Copyright (c) 1997 O'Reilly & Associates.
// You may study, use, modify, and distribute this example for any purpose.
// This example is provided WITHOUT WARRANTY either expressed or implied.
// Chapter 8 -- The Temperature class
package BeansBook.Simulator;
import java.beans.*;
// the temperature bean class definition
public class Temperature
implements TemperaturePulseListener, // listens for temperature pulses
java.io.Serializable // declare Serializable
{
// support object for bound property listeners
protected PropertyChangeSupport boundSupport;
// the current temperature
protected double theTemperature = 22.0;
// constructor
public Temperature()
{
// construct the support object
boundSupport = new PropertyChangeSupport(this);
}
// add a property change listener
public void addPropertyChangeListener(PropertyChangeListener l)
{
// defer to the support object
boundSupport.addPropertyChangeListener(l);
}
// remove a property change listener
public void removePropertyChangeListener(PropertyChangeListener l)
{
// defer to the support object
boundSupport.removePropertyChangeListener(l);
}
// get the value of the Temperature property
public double getTemperature()
{
return theTemperature;
}
// set the value of the Temperature property
public void setTemperature(double t)
{
// don't bother if the value didn't change
if (t == theTemperature)
return;
// save the old value
Double old = new Double(theTemperature);
// save the new value
theTemperature = t;
// fire the property change event
boundSupport.firePropertyChange("Temperature", old, new Double(t));
}
// handle a temperature pulse event
public void temperaturePulse(TemperaturePulseEvent evt)
{
// get the pulse temperature
double p = evt.getPulseTemperature();
// get the current temp
double c = getTemperature();
// if the pulse temperature is greater than the current temperature
if (p > c)
{
// only change if the difference is more than 1
if ((p - c) >= 1.0)
{
// add 1 to the current temperature
setTemperature(c + 1.0);
}
}
else if (p < c) // pulse less than the current temperature
{
// only change if the difference is more than 1
if ((c - p) >= 1.0)
{
// subtract 1 from the current temperature
setTemperature(c - 1.0);
}
}
}
}
|