0

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.

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
Rich Oliver
  • 6,001
  • 4
  • 34
  • 57

1 Answers1

3

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           
      }
   }
}
Rich Oliver
  • 6,001
  • 4
  • 34
  • 57