Search code examples
scalauser-inputvalidationtextinputscala-swing

Scala Swing: verifying Integer input forTextfield


I have a TextField that I wish to get an integer input from. In the previous c# Wpf version, I subscribe to the PreviewTextInput as follows:

private void PrevInp(object sender, TextCompositionEventArgs e)
{
   int temp;
   if (!(int.TryParse(e.Text, out temp)))
      e.Handled = true;
   else
      if (TextAltered == false)
      {
         inp.Text = "";
         TextAltered = true;
      }
}

Hopefully I can do something a little cleaner in Scala. I see you can set a function for inputVerifier, but the inputVerifier is only called when the TextField loses focus.

I can use the KeyTyped event like so:

val intF = new TextField(defInt.toString, 5)
{
   inputVerifier = myV _
   listenTo(keys, this)
   reactions += { case e: KeyTyped => text = text.filter(_.isDigit)}

   def myV(v: Component ): Boolean = text.forall(_.isDigit) 

}

But the new key pressed is added after the filter is applied.


Solution

  • The answer is to use event.consume as follows

    val intF = new TextField(defInt.toString, 5)
    {
       inputVerifier = myV _
       listenTo(keys)
       reactions +=
       {
          case e: KeyTyped =>     
          {
             if (!e.char.isDigit)
                e.consume           
          }
       }
    }