0

I am writing a generic JFormattedTextfield InputVerifier to check range for various types, e.g. Integer and Float. The only way that I have been successful so far is to assign an enum based on getClassName and then use switch statements to do parsing, comparisons, etc. Can anyone recommend something simpler/better? Here is some code that illustrates what I've done so far:

// Constructor:
public PrimitiveVerifier(String minVal, String maxVal)  throws IllegalArgumentException
{      
  String className = getUnqualifiedClassName(this);
    
  if (className.equals("Integer"))     _type = PrimitiveTypeEnum.INT_CLASS;
  else if (className.equals("Long"))   _type = PrimitiveTypeEnum.LONG_CLASS;
  else if (className.equals("Float"))  _type = PrimitiveTypeEnum.FLOAT_CLASS;
  else if (className.equals("Double")) _type = PrimitiveTypeEnum.DOUBLE_CLASS;
  else
    throw new IllegalArgumentException("PrimitiveVerifier implements only Integer, Long, Float, and Double types");
}

private Object parseStringToNumber(String txt)
{
  switch(_type)
  {
    case INT_CLASS:    return Integer.parseInt(txt);
    case LONG_CLASS:   return Long.parseLong(txt);
    case FLOAT_CLASS:  return Float.parseFloat(txt);
    default:           return Double.parseDouble(txt);
  }
}

private boolean IsLessThan(T x, T y)
{
  switch(_type)
  {
    case INT_CLASS: return return (Integer)x < (Integer)y;
    case LONG_CLASS: return return (Long)x < (Long)y;
    case FLOAT_CLASS: return (Float)x < (Float)y;
    default: return (Double)x < (Double)y;
    }
  }

public boolean verify(JComponent input)
{
  JFormattedTextField textField = (JFormattedTextField)input;
     
  textField.setForeground(VALID_COLOR);
            
  String text = textField.getText();    // Get control text
  
  if (text.length() == 0) return true;  // Empty textfield is OK
    
  T value = null;
     
  try                    // Parseable?
  {
    // Note: Parse failed unless fg color was black
    value = (T) parseStringToNumber(text);
  }
  catch(Exception e)
  {
    textField.setForeground(INVALID_COLOR);
  }
                         // Parse failed?
  if (textField.getForeground().equals(INVALID_COLOR))
    return false;
                         // Out of range?
  if (IsLessThan(value, _min) || IsLessThan(_max, value)) )
  {
    setTextValid(textField, false);
    return false;   
  }
     
  return true;   
}

Thanks!

1
Contributor
1
Reply
2
Views
5 Years
Discussion Span
Last Post by lcweltman
0

Update: For some reason, verify() never executes. I do not have these problems in a non-generic version. I'd appreciate any thoughts on the matter.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.