/// Evolver Copyright 2000, Morgan McGuire
/// matrix@alum.mit.edu   http://graphics3d.com/matrix
import java.awt.*;
import javax.swing.*;
import java.lang.reflect.*;
import javax.swing.event.*;

/**
 * A BoundedRangeModel that connects to a field of type double and allows
 * it to vary in the range (0, 1)
 */
public class DoublePercentageFieldAdapter extends DefaultBoundedRangeModel
{
  /**
   * double field
   */
  private Field field = null;

  /**
   * Object this slider is connected to.
   */
  private Object instance = null;

  public DoublePercentageFieldAdapter(Object instance, String fieldName)
  {
    super(0, 0, 0, 100);
    
    try {
      field = instance.getClass().getDeclaredField(fieldName);
    } catch (NoSuchFieldException e) {
      throw new Error("No field " + fieldName);
    }

    if (!field.getType().toString().equals("double")) {
      throw new Error("Field must be of type double");
    }
    
    this.instance = instance;
  }

  public int getValue()
  {
    int v = 0;
    try {      
      v = (int)Math.round(field.getDouble(instance) * 100);
    } catch (IllegalAccessException e) {
      throw new Error("");
    }
    return v;
  }

  public void setValue(int newValue)
  {
    try {
      field.setDouble(instance, newValue / 100.0);
    } catch (IllegalAccessException e) {
      throw new Error("");
    }
  }
}
