Is there a convenient way to add a filter to input to a scala.swing.TextComponent, so that the user can only input integers/floats/whatever? Especially, is there a way to filter pastes into a text field? In Java, I’ve used a DocumentFilter to do that. I’ve tried a few variations on this:
object inputField extends TextField{
peer.getDocument.asInstanceOf[AbstractDocument].setDocumentFilter(new DocumentFilter{
def insertString(fb: FilterBypass, offs: Integer, str: String, a: AttributeSet){
if(str.forall((c)=>c.isDigit)) super.insertString(fb, offs, str, a)
}
def replace(fb: FilterBypass, offs: Integer, l: Integer, str: String, a: AttributeSet){
if(str.forall((c)=>c.isDigit)) super.replace(fb, offs, l, str, a)
}
})
}
Which isn’t working. Am I doing that wrong, or does Scala ignore document filters? Is there another way to do this? I might be ok with using an entirely java.swing GUI if that’s what it takes.
You can achieve this using reactions:
Update:
Oh, I agree, that fits only relatively trivial cases. I’ve found problem with your original solution: you use Integers where Ints needed, so your methods are just new ones, not implementations of methods of abstract class. Here’s how it works for me:
Notice the use of “override”. That’s how I got compiler error and corresponding IDE tip, that if I really want to override something with this, I have to change signature.