I'm trying to create a generic InputVerifier that checks to see if the data in the JComponent is within a specified range. For this, I made my generic type extend Comparable<> to ensure it could be compared.
What I'm getting caught up on is the following two things:
- JComponent doesn't have a getText() method, and there isn't a subclass to cast to that's used by common components like JTextField and JSpinner, which each have their different methods for getting values.
- I don't think I can specify that my generic type DataType must have a certain function signature. I was trying to see if I could enforce that it has a a constructor that takes in a single string (like Integer, Double, Float do), or to enforce that DataType must extend either Integer, Double, or Float, but I am not sure if this is possible with Java 7 Generics. It would be great if i could do something like:
DataType myData = new DataType(text);
Here is the class I have now. I made it abstract, so a subclass would have to know the type of JComponent involved to return the text, and then how to build up the comparable type for comparison. This can lead to many permutations given the different types of JComponents and Comparable types that could be in play. Is there a way to eliminate one or both of the issues I'v mentioned above?
import javax.swing.InputVerifier;
import javax.swing.JComponent;
public abstract class InputRangeVerifier<DataType extends Comparable<DataType>> extends InputVerifier {
private DataType m_min;
private DataType m_max;
public InputRangeVerifier(DataType min, DataType max) {
m_min = min;
m_max = max;
}
@Override
public boolean verify(JComponent component) {
String componentText = getComponentText();
DataType comparable = getComparableValue(componentText);
boolean greaterThanOrEqualToMin = comparable.compareTo(m_min) > 0;
boolean lessThanOrEqualToMax = comparable.compareTo(m_max) < 0;
boolean isInRange = greaterThanOrEqualToMin && lessThanOrEqualToMax;
return isInRange;
}
public abstract String getComponentText();
public abstract DataType getComparableValue(String text);
}