// file: $ISIP_IFC/class/java/ConfigPanel/FloatTextField.java
// version: $Id: FloatTextField.java 10227 2005-09-09 19:07:49Z stanley $

// import necessary java libraries
//

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.undo.*;

/**
   A text field for editing integer values
*/
public class FloatTextField extends JTextField  { 

    /**
     * Constructs an FloatTextField.
     *
     *  @param defval the default value
     *  @param size the field size
     */
    public FloatTextField(int defval, int size) {
  
	super("" + defval, size);
	setInputVerifier(new FloatTextFieldVerifier());

	setHorizontalAlignment(JTextField.RIGHT);

    }
    
    /**
     * Create default model.
     *
     * @return a Document object.
     */
    protected Document createDefaultModel() {  
	return new FloatTextDocument();
    }
    
    /**
     * Checks if the contents of this field is a valid integer.
     *
     * @return true of the field contents is valid.
     */
    public boolean isValid() {
	return FloatTextDocument.isValid(getText());
    }
    
    /**
     * Gets the numeric value of the field contents.
     *
     * @return the number that the user typed into the field, or
     *  0 if the field contents is not valid.
     */
    public float getValue() {  
	try {
	    return Float.parseFloat(getText());
	}
	catch(NumberFormatException e) {
	    return 0;  
	}
    }
}


/**
 * A verifier that checks if the contents of a text component
 * is a valid integer.
 */
class FloatTextFieldVerifier extends InputVerifier {
    public boolean verify(JComponent component) {
	String text = ((JTextComponent)component).getText();
	return FloatTextDocument.isValid(text);
    }
}

/**
 * A document that can only hold valid integers or their 
 * substrings
 */
class FloatTextDocument extends PlainDocument {
  
    public void insertString(int offs, String str, 
			     AttributeSet a) 
	throws BadLocationException {
  
	if (str == null) return;
	
	String oldString = getText(0, getLength());
	String newString = oldString.substring(0, offs)
	    + str + oldString.substring(offs);
	
	if (canBecomeValid(newString))
	    super.insertString(offs, str, a);
    }
    
    /**
     * A helper function that tests whether a string is a valid
     * integer
     *
     * @param s a string
     * @return true if s is a valid integer
     */
    public static boolean isValid(String s) {
	try {
	    Float.parseFloat(s);
	    return true;
	}
	catch(NumberFormatException e) {	    
	    return false; 
	}
    }
    
    /**
     * A helper function that tests whether a string is a 
     * substring of a valid integer
     *
     * @param s a string
     * @return true if s can be extended to a valid integer
     */
    public static boolean canBecomeValid(String s) {
	
	return s.equals("") || s.equals("-") || isValid(s);
    }
}
